【问题标题】:Swift protocol isn't triggering Objective C protocol methodSwift 协议没有触发 Objective C 协议方法
【发布时间】:2016-09-08 13:22:55
【问题描述】:

我有一个 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,但我不明白为什么。谁能告诉我我错过了什么?

【问题讨论】:

  • 发布您添加子视图控制器的代码=
  • 你在哪里设置了代理?
  • 你还没有设置委托属性,这就是为什么它的 nil 并且没有被触发
  • 你能告诉我在哪里设置委托属性吗?我以为它被设置在 ChildViewController 类主体的第一行。

标签: ios objective-c swift protocols viewcontroller


【解决方案1】:

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

以同样的方式设置childVC 的框架属性稍后在MainViewController 中,您还需要将委托设置为MainViewController 的此实例。

例如

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

【讨论】:

  • 呃!!谢谢,西蒙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
相关资源
最近更新 更多