需求很简单,通过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;
当时我们就震惊了~~~