今天我发现一个奇怪的事情,似乎我的UIView
可以自动获取对我的UIViewController
的引用
我的UIView
声明一个 Controller 属性:
@interface YLSFirstView : UIView
@property YLSFirstViewController *controller;
@end
在 .m 文件中,我将该 Controller 设置为按钮目标:
[button addTarget:self.controller action:@selector(testAction) forControlEvents:UIControlEventTouchUpInside];
当然,在 Controller .m文件中,我实现了该操作(testAction
)
以下是代码实例并初始化UIView
和UIController
,但是我从未设置 Controller @property
!
YLSFirstViewController *first = [[YLSFirstViewController alloc] initWithNibName:nil bundle:[NSBundle mainBundle]];
first.view = [[YLSFirstView alloc] initWithFrame:CGRectNull];
令我惊讶的是:当我点击按钮时,ViewController
中的操作“testAction
”被调用...
我对此很困惑,为什么UIView
中的@property
Controller 得到了正确的引用? iOS
中是否有一些潜规则?
PS:顺便说一句,有好几次(不是经常),按钮失去响应,当我点击它时,什么也没有发生。大多数时候,它运行得很好。不知道有没有和我上面描述的相关的。
请告诉我答案好吗?非常感谢
最佳答案
这不是 UIView 自动获取 UIViewController 的引用,而是响应者链。
我在苹果开发库中找到了这段文字,引用是here
对于操作消息,当用户操作控件(例如按钮或开关)并且操作方法的目标为 nil 时,消息将通过从控件 View 开始的响应者链发送。
下图演示了响应者链路径,您应该知道,如果初始对象( HitTest View 或第一个响应者)不处理事件,UIKit 会将事件传递给链中的下一个响应者。
如图所示,UIViewController位于响应者链中,因此如果UIViewController的最顶层 View (这里是YLSFirstView)无法处理事件,它将传递给它的UIViewController(这里是YLSFirstViewController) .
关于ios - UIView 可以自动获取 UIViewController 的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20835742/