Swift 协议未触发 Objective C 协议方法

Swift protocol isn't triggering Objective C protocol method

我有一个 Swift 视图控制器,它定义了 Objective-C 视图控制器中应遵循的协议:

ChildViewController.swift

@objc public protocol ChildViewControllerDelegate {
    func closeChild();
}

@objc public class ChildViewController: UIViewController{

    var delegate: ChildViewControllerDelegate?

    @IBAction func childCloseButton(sender: UIButton) {
       delegate?.closeChild()
    }

}

MainViewController.m

@interface MainViewController () <ChildViewControllerDelegate>

@end

@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???");
}

@end

当我点击 UI 上的 "childCloseButton" 时,MainViewController.m 中的 "closeChild" 方法似乎没有被调用。通过调试器,我发现 "delegate" 属性 ChildViewController.swift 设置为 nil 但我不明白为什么。有人可以告诉我我错过了什么吗?

ChildViewController 正文中的第一行是创建一个可选的 属性。这是零,直到设置了一些东西。这里与委托没有什么特别之处,这只是简单的面向对象编程。

与稍后在MainViewController中设置childVC的框架属性的方式相同,您还需要将委托设置为MainViewController的这个实例.

例如

ChildViewController *childVC = [storyboard instantiateViewControllerWithIdentifier:@"childViewController"];
childVC.view.frame = childBox;
childVC.delegate = self