How to get a UIViewController from a UIView via co

2019-01-24 07:39发布

This question already has an answer here:

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];

5条回答
狗以群分
2楼-- · 2019-01-24 07:57

You can use the -nextResponder method to do it. According to http://developer.apple.com/library/ios/documentation/uikit/reference/UIResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/UIResponder/nextResponder , "UIView implements this method by returning the UIViewController object that manages it (if it has one) or its superview (if it doesn’t)"

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-24 08:00

You shouldn't save the reference to the view controller as it may change dynamically. Traverse the responder chain every time you need it.

查看更多
虎瘦雄心在
4楼-- · 2019-01-24 08:02

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;
...
查看更多
forever°为你锁心
5楼-- · 2019-01-24 08:02

You can use the following:

    UIViewController* yourViewController = 
                      (UIViewController*)[(YourAppDelegate*)
                      [[UIApplication sharedApplication] delegate] viewController];
查看更多
仙女界的扛把子
6楼-- · 2019-01-24 08:12

You can use

[(MyParentViewController *)[[self.view superview] nextResponder] doSomething];
查看更多
登录 后发表回答