OStack程序员社区-中国程序员成长平台

标题: ios - 默认纵向,一些特殊屏幕如何自动旋转或强制某些屏幕横向? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:47
标题: ios - 默认纵向,一些特殊屏幕如何自动旋转或强制某些屏幕横向?

在我的应用中,方向默认为纵向,但在某些特殊屏幕中,我希望 View Controller 自动旋转或强制方向为横向。

AppDelegate.swift 中:

class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

// portrait by default
var interfaceOrientations:UIInterfaceOrientationMask = .portrait {
    didSet{
        // force to portrait
        if interfaceOrientations == .portrait {
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue,
                                      forKey: "orientation")
        }
            // force to landscape
        else if !interfaceOrientations.contains(.portrait){
            UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue,
                                      forKey: "orientation")
        }
    }
}

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return interfaceOrientations
}

仅在纵向 vc 中:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    appDelegate.interfaceOrientations = .portrait
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    appDelegate.interfaceOrientations = .portrait
}

在自动旋转的vc中:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    appDelegate.interfaceOrientations = .allButUpsideDown
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    appDelegate.interfaceOrientations = .portrait
}

仅在横向 vc 中:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    appDelegate.interfaceOrientations = [.landscapeLeft, .landscapeRight]
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    appDelegate.interfaceOrientations = .portrait
}

但它仍然有错误...帮助我



Best Answer-推荐答案


你应该强制旋转:

UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")

您还必须启用自动旋转

override var shouldAutorotate: Bool{
    return true
}

当然,在您的项目设置中,您必须同时启用纵向和横向模式。

关于ios - 默认纵向,一些特殊屏幕如何自动旋转或强制某些屏幕横向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53205704/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4