アプリなどを開発するブログ

React Native / Swift / Ruby on Railsなどの学習メモ。


iOS マルチディスプレイ Swift 4

iOSでマルチディスプレイする際のコードをswiftで書き直してみたメモ。

 // 複数 window 対応

    private func checkForExistingScreenAndInitializeIfPresent() {
        if UIScreen.screens.count > 1 {
            // 外付けディスプレイを表す画面オブジェクトを取得する。
            let secondScreen = UIScreen.screens[1]
            print("secondScreen.preferredMode : ", secondScreen.preferredMode)

            // 画面の大きさを取得して、正しい大きさのウインドウを生成できるようにする。
            let screenBounds = secondScreen.bounds
            let screenBounds = CGRect(x: 0, y: 0, width: 2400, height: 1500)

            secondWindow = UIWindow(frame: screenBounds)
            secondWindow?.screen = secondScreen

            // 当初の表示内容を設定する
            if let vc = R.storyboard.settings().instantiateInitialViewController() {
                secondWindow?.rootViewController = vc
            }

            secondWindow?.isHidden = false
        }
    }

    private func setUpScreenConnectionNotificationHandlers() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleScreenDidConnectNotification(notification:)), name: NSNotification.Name.UIScreenDidDisconnect, object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(handleScreenDidDisconnectNotification(notification:)), name: NSNotification.Name.UIScreenDidDisconnect, object: nil)
    }

    @objc private func handleScreenDidConnectNotification(notification: Notification) {
        guard let newScreen: UIScreen = notification.object as? UIScreen else {
            print("setUpScreenConnectionNotificationHandlers 失敗")
            return
        }
        let screenBounds = newScreen.bounds
        if secondWindow == nil {
            secondWindow = UIWindow(frame: screenBounds)
            secondWindow?.screen = newScreen
            // ウインドウの初期UIを設定する。
        }
    }

    @objc private func handleScreenDidDisconnectNotification(notification: Notification) {
        if self.secondWindow != nil {
            // ウインドウを非表示にしてから削除する。
            self.secondWindow.hidden = true
            self.secondWindow = nil;
        }
    }