我有一个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
正文中的第一行正在创建一个可选属性。直到设置了某些东西,这才是零。这里与委托没有什么独特的关系,这仅仅是面向对象的编程。
以相同的方式设置childVC
稍后的frame属性MainViewController
,您还需要将委托设置为的实例MainViewController
。
例如
ChildViewController *childVC = [storyboard instantiateViewControllerWithIdentifier:@"childViewController"];
childVC.view.frame = childBox;
childVC.delegate = self
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句