經過UIView獲取UIViewController

需求很簡單,經過UIViewController.view內的任意控件獲取當前UIViewController;app

立馬開寫:spa

/**
 *    @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;
}

功能實現;code

自豪之餘,發現朋友發出新方法:blog

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

固然,他是百度的(鄙視之);get

兩人剛準備興奮發現另外一人發出:io

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

當時咱們就震驚了~~~class

相關文章
相關標籤/搜索