【原】iOS学习之在NSObject子类中获取当前屏幕显示的ViewController

时间:2022-11-21 05:01:36

 我们在非视图类中想要随时展示一个view时,需要将被展示的view加到当前view的子视图,或用当前view presentViewController,或pushViewContrller,这些操作都需要获取当前正在显示的ViewController。

代码如下:(详细理解请仔细阅读注释)

#pragma mark 获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
// 定义一个变量存放当前屏幕显示的viewcontroller
UIViewController *result = nil; // 得到当前应用程序的主要窗口
UIWindow * window = [[UIApplication sharedApplication] keyWindow]; // windowLevel是在 Z轴 方向上的窗口位置,默认值为UIWindowLevelNormal
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:]; // 获取视图的下一个响应者,UIView视图调用这个方法的返回值为UIViewController或它的父视图
id nextResponder = [frontView nextResponder]; // 判断显示视图的下一个响应者是否为一个UIViewController的类对象
if ([nextResponder isKindOfClass:[UIViewController class]]) {
result = nextResponder;
} else {
result = window.rootViewController;
}
return result;
}

代码说明:

  • 代码中使用的 UIApplication类 属性说明:

  keyWindow(@property(nonatomic, readonly) UIWindow *keyWindow)

   官网描述:

    The value of this property is YES when the window is the key window or NO when it is not. The key window receives keyboard and other non-touch related events. Only one window at a time may be the key window.

   个人理解:

    应用程序的主要窗口

  windows(@property(nonatomic, readonly) NSArray <__kindof UIWindow *> *windows)

   官网描述:

    This property contains the UIWindow objects currently associated with the app. This list does not include windows created and managed by the system, such as the window used to display the status bar.

   个人理解:

    获取应用程序中显示和隐藏的所有的Window窗口,放到一个数组中

  • 代码中使用的 UIWindow类 属性说明:

  windowLevel(@property(nonatomic) UIWindowLevel windowLevel)

   官网描述:

    Window levels provide a relative grouping of windows along the z-axis. All windows assigned to the same window level appear in front of (or behind) all windows assigned to a different window level. The ordering of windows within a given window level is not guaranteed.

   个人理解:

    Z轴 方向上的窗口位置,默认值为UIWindowLevelNormal

  • 代码中使用的 UIResponder类 中对象方法说明:

  - (UIResponder *)nextResponder

   官网描述:

    The UIResponder class does not store or set the next responder automatically, instead returning nil by default. Subclasses must override this method to set the next responder. UIView implements this method by returning the UIViewController object that manages it (if it has one) or its superview (if it doesn’t); UIViewController implements the method by returning its view’s superview; UIWindow returns the application object, and UIApplication returns nil.

   个人理解:

    返回下一个响应者,也就是在执行顺序中的下一个。