我有一个 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 ()
@kết thúc
@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???");
}
@kết thúc
当我单击 UI 上的“childCloseButton”时,MainViewController.m 中的“closeChild”方法似乎没有被调用。通过调试器,我发现“委托(delegate)”属性 ChildViewController.swift 设置为 nil 但我不明白为什么。有人可以告诉我我错过了什么吗?
ChildViewController
主体的第一行是创建一个可选属性。这是零,直到设置了一些东西。这里与委托(delegate)没有什么特别之处,这只是简单的面向对象编程。
与稍后在MainViewController
中设置childVC
的frame属性一样,您也需要将delegate设置为MainViewController<>
.
Ví dụ
ChildViewController *childVC = [storyboard instantiateViewControllerWithIdentifier:@"childViewController"];
childVC.view.frame = childBox;
childVC.delegate = self
Tôi là một lập trình viên xuất sắc, rất giỏi!