iOS 13 之后自定义 Window 不显示解决 (SceneDelegate)

  • iOS 13 以后苹果增加了 SceneDelegate 来管理窗口。
  • iOS 13 以前自定义个 Window 进行显示,下面两种方式都可以
    • 方式一:
    let newWindow = UIWindow()
    newWindow.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height:     
    UIScreen.main.bounds.size.height)
    newWindow.backgroundColor = UIColor.red
    newWindow.isHidden = false
    
    • 方式二:
    let newWindow = UIWindow()
    newWindow.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height:UIScreen.main.bounds.size.height)
    newWindow.backgroundColor = UIColor.red
    newWindow.windowLevel = UIWindow.Level.alert
    newWindow.makeKeyAndVisible()
    
  • iOS 13 以后新建或自定义的 Window 必须注册到 ``SceneDelegate 中
    • Swift
    if #available(iOS 13.0, *) {
       // 通知注册方式看场景进行添加,不需要可以去除
       NotificationCenter.default.addObserver(forName: UIScene.willConnectNotification, object: nil, queue: nil) { (note) in
           newWindow.windowScene = note.object as? UIWindowScene
       }
     // 主要注册
     for windowScene in UIApplication.shared.connectedScenes {
         if (windowScene.activationState == UIScene.ActivationState.foregroundActive) {
             newWindow.windowScene = windowScene as? UIWindowScene
         }
     }
    }
    
    • OC 注册
    if (@available(iOS 13.0, *)) {
      // 通知注册方式看场景进行添加,这里我就不写了
      // 主要注册
      for (UIWindowScene *windowScene in [UIApplication sharedApplication].connectedScenes) {
          if (windowScene.activationState == UISceneActivationStateForegroundActive) {
            newWindow.windowScene = windowScene;
            break;
        }
      }
    }
    

注意:

  • 在有些方法中注册时[UIApplication sharedApplication].connectedScenes为空,可以 延时 进行注册,比如didFinishLaunchingWithOptions方法执行时会为空。

你可能感兴趣的:(iOS 13 之后自定义 Window 不显示解决 (SceneDelegate))