当前view和当前controller [iOS] Objective-C

转载请注明本文的出处@TEASON

这两个很常用 , 很有用 ,也比较有意思
开门见山

1.获取当前view

判断view是否在当前屏幕上显示很简单,通过window即可.
这里你可以释放一些变量或者关闭一些线程队列或者timer的释放等等.

if (!self.view.window) {
  // do something 
}

2.获取当前controller

当前controller
很重要,原理是通过响应者链做到的,这里不展开了.
理解概念博客里有相关文章.点击跳转

- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

你可能感兴趣的:(当前view和当前controller [iOS] Objective-C)