一、实现原理:
通过消息响应者链找到UIView所在的UIViewController
UIView类继承于UIResponder,通过UIResponder的next方法来获取UIViewController.
如果next返回是空,则继续向上遍历superview并再次使用next方法获取。这样一直找下去,直到找到或抛出异常。
二、实现代码
通过扩展UIView,给其添加个viewController方法,从而让我们可以获得任意视图对象(View)所属视图控制器
Swift
func viewController() -> UIViewController? {
for view in sequence(first: self.superview, next: { $0?.superview }) {
if let responder = view?.next {
if responder.isKind(of: UIViewController.self){
return responder as? UIViewController
}
}
}
return nil
}
Objective-C
-(UIViewController *)viewController{
UIViewController *viewController = nil;
UIResponder *next = self.nextResponder;
while (next) {
if ([next isKindOfClass:[UIViewController class]]) {
viewController = (UIViewController *)next;
break;
}
next = next.nextResponder;
}
return viewController;
}
网友评论