xcode 从 chid UIView 访问父视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9151230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access parent view from a chid UIView
提问by user930731
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.
我有一个带有 xib 的 UIViewController,并使用 Interface Builder 添加了一个子 UIView。在子 UIView 中,当我单击该视图中的一个对象时,我希望能够更改整个窗口的标题。
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?
在父 UIViewController 上。但是有什么方法可以从孩子内部访问父标题吗?
I've tried
我试过了
self.superview.title = @"i";
self.parentViewController.title = @"hi";
but neither work. Any help much appreciated
但都不起作用。非常感谢任何帮助
thanks
谢谢
采纳答案by Tommy
self.superview.title = @"i";
evaluates to an object of type UIView
, and UIView
has no title
property. UIViewController
s have a parentViewController
property but UIView
s don't.
self.superview.title = @"i";
计算为 type 的对象UIView
,并且UIView
没有title
属性。UIViewController
s 有一个parentViewController
财产,但UIView
s 没有。
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 like UIButton
already are, but if it's a custom UIView
subclass then you can just change it into a UIControl
subclass since UIControl
is itself a subclass of UIView
), then in your controller add something like:
所以根本的问题是你没有正确地分离你的控制器和你的视图类。你通常做的是让你想要捕捉的视图点击的子类UIControl
(UIButton
已经是这样的,但如果它是一个自定义UIView
子类,那么你可以将它更改为UIControl
子类,因为UIControl
它本身就是 的子类UIView
),然后在您的控制器中添加如下内容:
- (void)viewDidLoad
{
[super viewDidLoad];
// we'll want to know if the view we care about is tapped;
// we've probably set up an IBOutlet to it but any way of
// getting to it is fine
[interestingView
addTarget:self
action:@selector(viewTapped:)
forControlEvents:UIControlEventTouchDown];
// UIButtons use UIControlEventTouchUpInside rather than
// touch down if wired up in the interface builder. Pick
// one based on the sort of interaction you want
}
// so now this is exactly like an IBAction
- (void)viewTapped:(id)sender
{
self.title = @"My new title";
}
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.
因此,您明确地不向视图投资有关其在视图层次结构中的位置或视图控制器打算如何操作的任何知识。如果它收到用户交互,你只需告诉它给你一个喊叫。