views:

362

answers:

1

Guys,

There is a way to get a view controller reference from a UIView object? I need something like this:

MyParentViewController *myParentViewController = [self.view.superview controller];

Thanks in advance.

+5  A: 

UIView does not have reference to UIViewController by default.You can add it to your UIView subclass and set it when you create UIView in UIViewController.

If you are looking for parent of the viewcontroller, each UIViewController has property parentViewController, but if you want to access this from UIView you need to first get to your UIViewController.

You can see example how to create reference to your UIViewController in your subclass of UIView and how/where to set it up in View Controller Programming guide for iPhone, see section Creating the View Programmatically in Defining a Custom View Controller Class, here is the example, for more details see the linked Metronome example.

 - (void)loadView {

    self.wantsFullScreenLayout = YES;

    MetronomeView *view = [[MetronomeView alloc]
                          initWithFrame:[UIScreen mainScreen].applicationFrame];
    view.metronomeViewController = self;
    self.view = view;
    self.metronomeView = view;

    [view release];
}

In header:

@interface MetronomeView : UIView {
    MetronomeViewController *metronomeViewController;
...
stefanB
Many thanks for your answer!
R31n4ld0_