iOS13之前的获取方式
UIApplication.sharedApplication.keyWindow
iOS13 之后新增了UIWindowScene,keyWindow的获取也有了新的方式,将来肯定会移除该字段,记录下方法提前适配。
@property(nullable, nonatomic,readonly) UIWindow *keyWindow
API_DEPRECATED("Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes", ios(2.0, 13.0));
直接上代码
+ (UIWindow *)zyl_keyWindow
{
if (@available(iOS 13.0, *)) {
for (UIWindowScene *windowScene in UIApplication.sharedApplication.connectedScenes) {
if (windowScene.activationState == UISceneActivationStateForegroundActive) {
for (UIWindow *window in windowScene.windows) {
if (window.isKeyWindow) {
return window;
}
}
break;
}
}
} else {
return UIApplication.sharedApplication.keyWindow;
}
return nil;
}
也有使用以下方式的
UIApplication.sharedApplication.delegate.window
但是现在新建项目 UIApplication 里不会创建 window,需要手动创建 window属性。SceneDelegate里也要加上window属性,否则调用会崩溃。