美文网首页iOS
Swift 4.0 横竖屏问题

Swift 4.0 横竖屏问题

作者: Desmond_ | 来源:发表于2018-03-29 11:50 被阅读146次

我们开发的 iPhone 应用一般都是固定竖屏,但项目中不乏特定几个视图也需要支持横屏。之前 Swift 2.3 中,只需自定义 UIViewController,重写以下方法:

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
        return UIInterfaceOrientation.Portrait
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.Portrait
}

override func shouldAutorotate() -> Bool {
        return false
}

要固定竖屏的继承该类就行了。

Swift 4.0 中上述三个重写方法已经变成属性了。这里推荐一篇文章,里面有几种方法设置横竖屏,我使用的是文章中最后一种方法,具体代码就不赘述了,直接可参考原文章。

至于如何监听界面旋转,原文章中已经有了很好的总结:
1、用 NotificationCenter 进行监听;
2、建议监听界面方向而不是设备方向;

Swift 2.3 中的重写 didRotateFromInterfaceOrientation 方法已经弃用,这里可用另一种方法来实现(参考链接):

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { (_) in
            let orient = UIApplication.shared.statusBarOrientation
            if orient.isPortrait {
                print("竖屏了")
            } else if orient.isLandscape {
                print("横屏了")
            }
            
        }) { (_) in
            print("rotation completed")
        }
        super.willTransition(to: newCollection, with: coordinator)
    }

更新时间:2018年04月08日
上面提到的通过重写 willTransition 方法来监听横竖屏切换,测试发现这是一个类似全局的方法,即在 viewControllerA 中重写了该方法,push 到 viewControllerB 后,在 viewControllerB 中切换横竖屏,该方法也会执行!
那监听方法还是换成通知吧:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
            UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        }
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(handleOrientationChange(notification:)),
                                               name:NSNotification.Name.UIApplicationDidChangeStatusBarOrientation,
                                               object: nil)
    }

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        NotificationCenter.default.removeObserver(self)
        UIDevice.current.endGeneratingDeviceOrientationNotifications()
    }

@objc private func handleOrientationChange(notification: Notification) {
        // 获取设备方向
        let statusBarOrientation = UIApplication.shared.statusBarOrientation
        if statusBarOrientation.isPortrait {
            print("竖屏了")
            
        } else if statusBarOrientation.isLandscape {
            print("横屏了")
            
        }
    }

相关文章

网友评论

    本文标题:Swift 4.0 横竖屏问题

    本文链接:https://www.haomeiwen.com/subject/ymcucftx.html