Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access parent view from a chid UIView

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

like image 817
user930731 Avatar asked Feb 05 '12 17:02

user930731


1 Answers

self.superview.title = @"i"; evaluates to an object of type UIView, and UIView has no title property. UIViewControllers have a parentViewController property but UIViews 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 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:

- (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.

like image 94
Tommy Avatar answered Nov 15 '22 04:11

Tommy