Vee Vee - 1 year ago 78
Objective-C Question

Swift protocol isn't triggering Objective C protocol method

I have a Swift view controller that defines a protocol that should be followed in an Objective-C view controller:


@objc public protocol ChildViewControllerDelegate {
func closeChild();

@objc public class ChildViewController: UIViewController{

var delegate: ChildViewControllerDelegate?

@IBAction func childCloseButton(sender: UIButton) {



@interface MainViewController () <ChildViewControllerDelegate>


@implementation MainViewController
- (void)viewDidAppear:(BOOL)animated {
// creating frame for child and placing it on the bottom of the screen
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat yOffset = self.view.frame.origin.y;
CGFloat childHeight = (8/15) * screenWidth;
CGRect child = CGRectMake(0, screenHeight - yOffset - childHeight, screenWidth, childHeight);

// adding storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"child" bundle:nil];
ChildViewController *childVC = [storyboard instantiateViewControllerWithIdentifier:@"childViewController"];
childVC.view.frame = childBox;
[self addChildViewController: childVC];
[self.view addSubview:childVC.view];

- (void) closeChild {
NSLog(@"Why doesn't this get trigger???");


When I click the "childCloseButton" on the UI, the "closeChild" method in MainViewController.m doesn't seem to get called. Stepping through the debugger, I discovered the "delegate" property ChildViewController.swift is set to nil but I don't understand why. Can somebody tell me what I'm missing?

Answer Source

The first line in ChildViewController's body is creating an optional property. This is nil until set with something. There is nothing unique here to do with delegates, this is just simply object oriented programming.

In the same way to set the frame property of childVC later on in MainViewController, you need to also set the delegate to be this instance of MainViewController.


ChildViewController *childVC = [storyboard instantiateViewControllerWithIdentifier:@"childViewController"];
childVC.view.frame = childBox;
childVC.delegate = self
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download