访问 window 属性 应用程序委托 iOS

accessing window property app delegate iOS

我是 IOS 的新手。我有一个简单的问题。我想从另一个文件访问 AppDelegate.h 文件中的 window 属性。另外,我无法将 AppDelegate.h 文件导入到另一个文件,因为这些文件会不断地相互导入。是否可以从 AppDelegate.h 文件外部访问 window 属性?

谢谢

选项 1 使用 KVC

id appDelegate = [UIApplication sharedApplication].delegate;
UIWindow *window = [appDelegate valueForKey:@"window"];

Option2 使用 UIApplication

的 keywindow 属性
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];

This property holds the UIWindow object in the windows array that is most recently sent the makeKeyAndVisible message.

Option3 使用windoss 属性 of UIApplication

NSArray *array = [[UIApplication sharedApplication] 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.

The windows in the array are ordered from back to front by window level; thus, the last window in the array is on top of all other app windows.

像下面这样创建 AppDelegate 的全局变量,这样您就可以随时 use/access 属性 AppDelegate。

appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

并且您可以通过

访问 window 对象
appDelegate.window ...

注意:不要忘记在 AppDelegate 的 .h 文件中添加声明对象

AppDelegate *appDelegate;