在NSObject子類中擷取當前螢幕顯示的ViewController,當前viewcontroller
我們在非視圖類中想要隨時展示一個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:0]; // 擷取視圖的下一個響應者,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視窗,放到一個數組中
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.
個人理解:
返回下一個響應者,也就是在執行順序中的下一個。