DoKit icon indicating copy to clipboard operation
DoKit copied to clipboard

iOS UIView+Doraemon 分类中 -(UIViewController*)viewController 方法能否返回当前 UIView 的 ViewController?

Open yidahis opened this issue 2 years ago • 0 comments

iOS UIView+Doraemon 分类文件中 -(UIViewController*)viewController 方法内部实现如下:

-(UIViewController*)viewController{
    for(UIView *next =self.superview ; next ; next = next.superview){
        UIResponder*nextResponder = [next nextResponder];
        if([nextResponder isKindOfClass:[UIViewController class]]){
            return(UIViewController*)nextResponder;
        }
    }
    return nil;
}

for 循环中初始值为 self.superview 会导致获无法获取到真实的 ViewController , 而是其 NavigationViewController。例如直接用一个ViewController 的 View 调用此方法,得到的就是一个 NavigationViewController。因为该 View 的 nextResponder 实际上就是其 ViewController , 但是该 View 的 superview 的 nextResponder 就肯定不是原来那个 ViewController 了

yidahis avatar Mar 15 '22 09:03 yidahis