从子 UIView 访问父视图
我有一个带有 xib 的 UIViewController 并使用 Interface Builder 添加了一个子 UIView。 在子 UIView 中,当我单击该视图中的对象时,我希望能够更改整个窗口的标题。
现在我通常会
self.title = @"hi";
在父 UIViewController 上进行该设置。但是有什么方法可以从孩子内部访问父头衔吗?
我已经尝试过
self.superview.title = @"i";
self.parentViewController.title = @"hi";
,但都不起作用。 任何帮助
非常感谢
I have a UIViewController with an xib and using Interface Builder I've added a child UIView.
Within the child UIView, when I click on an object within that view, I want to be able to alter the title of the whole window.
Now I'd normally do that setting
self.title = @"hi";
on the parent UIViewController. But is there any way I can access the parent title from within the child?
I've tried
self.superview.title = @"i";
self.parentViewController.title = @"hi";
but neither work.
Any help much appreciated
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
self.superview.title = @"i";
计算结果为UIView
类型的对象,并且UIView
没有title属性。
UIViewController
有parentViewController
属性,但UIView
没有。因此,根本问题是您没有正确分离控制器和视图类。您通常要做的就是让您想要捕获
UIControl
子类上的点击的视图(像UIButton
这样的东西已经存在,但如果它是自定义的UIView
子类,那么您可以将其更改为UIControl
子类,因为UIControl
本身就是UIView
的子类),然后在您的控制器添加类似的内容:所以你明确地不要向视图投入任何有关其在视图层次结构中的位置或视图控制器打算如何操作的知识。您只需告诉它在收到用户交互时向您大声喊叫即可。
self.superview.title = @"i";
evaluates to an object of typeUIView
, andUIView
has notitle
property.UIViewController
s have aparentViewController
property butUIView
s don't.So the fundamental problem is that you're not properly separating your controller and your view classes. What you'd normally do is make the view you want to catch taps on a subclass of
UIControl
(which things likeUIButton
already are, but if it's a customUIView
subclass then you can just change it into aUIControl
subclass sinceUIControl
is itself a subclass ofUIView
), then in your controller add something like:So you explicitly don't invest the view with any knowledge about its position within the view hierarchy or how your view controllers intend to act. You just tell it to give you a shout out if it receives a user interaction.