shouldAutoRotate不能在swift中工作

时间:2014-08-28 15:27:12

标签: ios uinavigationcontroller swift rotation

我知道如果VC有navigationController,它应该包含this之类的内容。但是迅速呢?如何使用shouldAutoRotate在VC中调用navigationController?我的navigationController标准类UINavigationController(非自定义)。我想让除了单身之外的所有VC都使shouldAutoRotate为假。据我所知,没有其他方法可以使用" Portrait"并使其可以旋转单个VC

4 个答案:

答案 0 :(得分:2)

将它放在视图控制器中:

override func shouldAutorotate() -> Bool {

     return false // or true for the VC that allows landscape
}

答案 1 :(得分:1)

Swift 3需要类型为var而不是func:

override var shouldAutorotate: Bool {
    return false
}

答案 2 :(得分:1)

Swift 4

我找到的最有效的方法是在给定的UIViewController上添加此扩展 - 首先进入视图:

extension UINavigationController {

    override open var shouldAutorotate: Bool {
        get {
            if let visibleVC = visibleViewController {
                return visibleVC.shouldAutorotate
            }
            return super.shouldAutorotate
        }
    }

    override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        get {
            if let visibleVC = visibleViewController {
                return visibleVC.preferredInterfaceOrientationForPresentation
            }
            return super.preferredInterfaceOrientationForPresentation
        }
    }

    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        get {
            if let visibleVC = visibleViewController {
                return visibleVC.supportedInterfaceOrientations
            }
            return super.supportedInterfaceOrientations
        }
    }

}

然后你需要覆盖shouldAutorotate函数。将其添加到您的UIViewController类:

override open var shouldAutorotate: Bool {
    return false
}

您导航到的任何UIViewController,您只需覆盖shouldAutorotate函数并将其设置为您喜欢的任何内容(返回true或false)。

对于以模态方式显示的任何视图,请覆盖supportedInterfaceOrientations:

override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .all
}

答案 3 :(得分:0)

适用于iOS13.4模拟器-

import UIKit

var autorotateEnabled: Bool = true

public class MainViewController : UIViewController {

    @IBAction func lockAutoRotate(_ sender: Any) {
        autorotateEnabled = !autorotateEnabled
    }
    
    @IBAction func SetOrientationTest(_ v: UIView){
        // Change the desired orientation of this activity.
        if UIDevice.current.orientation == .portrait {
            UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        } else {
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        }
    }
    
    override public func viewDidLoad() {
        var savedInstanceState = UserDefaults.standard.dictionaryRepresentation()
        super.viewDidLoad()
    }
}

extension UINavigationController {
    override open var shouldAutorotate: Bool {
       return autorotateEnabled
    }
}