tvOS中的自定义UIWindow使应用程序无法响应键盘输入

时间:2017-05-14 10:50:35

标签: tvos uiwindow

在tvOS中,如果我使用自定义UIWindow实例,应用程序将停止响应模拟器中的键盘和遥控器。我应该在UIWindow实例上设置任何变量或属性吗?

class AppDelegate: UIResponder, UIApplicationDelegate {

    lazy var window : UIWindow? = {
        let screen = UIScreen.main
        let w = UIWindow(frame: screen.bounds)
        return w
    }()

    // ...
}

原因是我需要将UIWindow子类化为自定义色调,并通过traitCollectionDidChange响应暗/亮模式更改。

这是在tvOS 10.2.1中

2 个答案:

答案 0 :(得分:0)

您需要在UIWindow的实例中调用makeKeyAndVisible()

https://developer.apple.com/reference/uikit/uiwindow/1621601-makekeyandvisible

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func applicationDidFinishLaunching(_ application: UIApplication) {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = yourRootViewController
        window?.makeKeyAndVisible()
    }
}

答案 1 :(得分:-1)

如果需要自定义UIWindow,显然需要实例化故事板并显示窗口。仅提供UIWindow实例是不够的。

首先,从主应用的UIMainStoryboardFile文件中删除密钥Info.plist

然后在应用程序中添加代码确实启动处理程序:

  1. 实例化窗口并分配给应用委托的属性。
  2. 实例化故事板。
  3. 实例化初始视图控制器
  4. 将视图控制器分配给窗口。
  5. 显示窗口。
  6.     @UIApplicationMain
        class AppDelegate: UIResponder, UIApplicationDelegate {
    
            var window : UIWindow?
    
            // ...
    
            func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
                window = MainWindow(frame: UIScreen.main.bounds)
                // We need to instantiate our own storyboard instead of specifying one in `Info.plist` since we need our own custom `UIWindow` instance.
                // Otherwise if we just create the custom UIWindow instance and let the system creates a storyboard,
                // then the application won't respond to the keyboard/remote (user input).
                let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
                window?.rootViewController = storyboard.instantiateInitialViewController()
                defer {
                    window?.makeKeyAndVisible()
                }
    
                // ... All other setup code
            }
    
            // ...
    
        }