一、实现原理:
通过消息响应者链找到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;
}