通过UIView获取UIViewController

原文地址

通过UIViewController.view内的任意控件获取当前UIViewController;

方法一

/**
 *    @brief    通过viewController内的view,获取Controller
 * 
 *    @param     view     subView
 *
 *    @return    UIViewController
 */
- (UIViewController *)recursionView2ViewController:(UIView *)view
{
    __block UIViewController *viewController;
    __block void (^blocks)(UIView *) = nil;
    blocks = ^(UIView *view)
    {
        if([view.superview isKindOfClass:NSClassFromString(@"UIViewControllerWrapperView")])
        {
            Ivar ivar = class_getInstanceVariable([UIView class], "_viewDelegate");
            viewController = object_getIvar(view, ivar);
        }
        else blocks(view.superview);
    };
    blocks(view);
    return viewController;
}

方法二
···

  • (UIViewController *)findViewController:(UIView *)sourceView
    {
    id target=sourceView;
    while (target) {
    target = ((UIResponder *)target).nextResponder;
    if ([target isKindOfClass:[UIViewController class]]) {
    break;
    }
    }
    return target;
    }
    ···

方法三

//nav为root UINavigationController
UIViewController *viewController = ((AppDelegate *)[UIApplication sharedApplication].delegate).nav.visibleViewController;

你可能感兴趣的:(通过UIView获取UIViewController)