【问题标题】:Orientation support in single view controller swift 5单视图控制器 swift 5 中的方向支持
【发布时间】:2019-06-03 04:47:51
【问题描述】:

我需要在单视图控制器中支持方向

我尝试但没有成功。现在在整个应用程序中定位。

override func viewDidLoad() {
    super.viewDidLoad()

    self.lockOrientation()
}

func lockOrientation() {
    let orientationValue = UIInterfaceOrientation.portrait.rawValue
    UIDevice.current.setValue(orientationValue, forKey: "orientation")
}

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .portrait
}

【问题讨论】:

标签: ios swift


【解决方案1】:

将以下代码放入AppDelegate

仅在项目常规设置中将设备方向保留为纵向

var restrictRotation: Bool = true

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if restrictRotation {
        return .portrait
    } else {
        return .all
    }
}

将您想要允许/禁用方向的代码放在下面。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.restrictRotation(false) //TRUE TO RESTRICT ORIENTATION && FALSE TO ALLOW ORIENTATION
}

func restrictRotation(_ restriction: Bool) {
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    appDelegate?.restrictRotation = restriction
}

【讨论】:

    【解决方案2】:

    问题已通过bmjohns 回答解决 请访问并检查。

    @bmjohns 回答更新版本

    斯威夫特 5

    // set orientations you want to be allowed in this property by default
    var orientationLock = UIInterfaceOrientationMask.all
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
            self.lockOrientation()
            return true
    }
    
    func unlockOriention () {
        self.orientationLock = .all
    }
    
    func lockOrientation() {
        self.orientationLock = .portrait
    }
    

    SecondViewController.swift

    同时支持方向

    override func viewDidLoad() {
            super.viewDidLoad()
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.unlockOriention()
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 2014-08-05
      相关资源
      最近更新 更多