Access parent view from chid UIView

I have a UIViewController with xib and using Interface Builder I added a child UIView. Inside the child UIView, when I click on an object in this view, I want to be able to change the title of the whole window.

Now I usually make this setting

self.title = @"hi"; 

on the parent UIViewController. But is there any way to access the parent type from the child?

I tried

 self.superview.title = @"i"; self.parentViewController.title = @"hi"; 

but do not work. Any help is much appreciated

thanks

+4
source share
1 answer

self.superview.title = @"i"; evaluated by an object of type UIView , and UIView does not have a title property. UIViewController have a parentViewController property, but UIView do not.

So the main problem is that you are not properly separating your controller and view classes. What you usually do is the view you want to grab the taps in a subclass of UIControl (which things like UIButton already exist, but if it's a custom subclass of UIView , then you can just change it to UIControl , since UIControl itself is a subclass of UIView ), then in your controller add something like:

 - (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"; } 

That way, you are clearly not investing in a view with any knowledge of its position in the view hierarchy or how your view controllers intend to act. You just tell him to give you a shout if he gets user interaction.

+2
source

Source: https://habr.com/ru/post/1394883/


All Articles