从 UIView 的子视图获取 UINavController?
我向 UIViewController 的内容视图添加了一个自定义子视图。从该子视图中,如何获取对超级视图控制器的引用? 谢谢
I added a custom subview to a UIViewController's content view. From that subview, how can I get a reference to the superview's controller?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的答案是“你做错了™”;-)
你不应该需要从视图引用视图控制器,并且你当然不应该在你的视图之一中保留视图控制器 - 否则你'最终会出现保留循环并泄漏内存。
Cocoa 提供了多种模式来解决这个问题:
使用委托: 定义一个名为 DemoViewDelegate 的协议,并向 DemoView 添加一个委托属性。然后让你的视图控制器实现这个协议。 重要提示:决不应该保留代表!您创建的任何委托属性都应设置为
分配
。请参阅Apple 的委托文档 或只是谷歌“委托模式”。使用响应者链:调用 UIApplication 的
sendAction:to:from:forEvent:
并将to:
设置为nil< /code> 让您的操作消息自动沿着响应者链路由到您的视图控制器。请参阅 Apple 的 Responder 文档 和更详细的操作消息文档。
使用通知:在此特定场景中不太常见,但您也可以让视图控制器侦听视图发送的通知。
The correct answer is "You're Doing It Wrong™" ;-)
You shouldn't need to reference to a view controller from a view, and you certainly should never retain a view controller in one of your views -- or you'll end up with a retain loop and leak memory.
Cocoa provides multiple patterns to solve this problem:
Use a delegate: Define a protocol called DemoViewDelegate and add a delegate property to DemoView. Then have your view controller implement this protocol. Important: delegates should never be retained! Any delegate property you create should be set to
assign
. See Apple's Delegation docs or just google "delegation pattern".Use the responder chain: Call UIApplication's
sendAction:to:from:forEvent:
and leaveto:
set tonil
to have your action message automatically routed up the responder chain to your view controller. See Apple's Responder docs and the more detailed Action Messages docs.Use a notification: Less common in this particular scenario, but you could also have your view controller listen for a notification, which the view sends.