gpt4 book ai didi

ios - Swift 协议(protocol)不触发 Objective C 协议(protocol)方法

转载 作者:行者123 更新时间:2023-11-28 16:12:37 26 4
gpt4 key购买 nike

我有一个 Swift View Controller ,它定义了一个在 Objective-C View Controller 中应该遵循的协议(protocol):

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 主体的第一行是创建一个可选属性。这是零,直到设置了一些东西。这里与委托(delegate)没有什么特别之处,这只是简单的面向对象编程。

与稍后在MainViewController中设置childVC的frame属性一样,您也需要将delegate设置为MainViewController<的这个实例.

例如

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

关于ios - Swift 协议(protocol)不触发 Objective C 协议(protocol)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39392163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com