首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >覆盖没有在Swift 3中工作的shouldAutorotate

覆盖没有在Swift 3中工作的shouldAutorotate
EN

Stack Overflow用户
提问于 2016-11-04 00:40:00
回答 6查看 24.8K关注 0票数 31

我试图阻止在一个UIViewController上旋转,但我无法做到这一点。

我在做这样的事情:

代码语言:javascript
复制
open override var shouldAutorotate: Bool {
    get {
        return false
    }
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    get {
        return .portrait
    }
}

UIViewControler仍然旋转。UIViewController位于以模式方式打开的UINavigationController中。

我从这里看了很多问题,没有一个答案对我有用。

在Swift 2中,我曾经覆盖shouldAutorotate,但是在Swift 3中,这个函数已经不存在了。

我怎样才能在Swift 3中做到我以前在Swift 2中所做的?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2016-11-04 16:27:08

我不知道为什么要投票结束这个问题,如果我能重复这种行为很多次。UIViewController位于以模式方式打开的UINavigationController中。

这就是我为解决这个问题所做的。

我创建这个类,并设置为包含要防止旋转的UINavigationControllerUIViewController

代码语言:javascript
复制
class NavigationController: UINavigationController { 

    override var shouldAutorotate: Bool {
        return false
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

}

就这样,这对我来说很管用

票数 45
EN

Stack Overflow用户

发布于 2017-09-07 07:12:43

将此代码添加到AppDelegate.swift

代码语言:javascript
复制
var orientationLock = UIInterfaceOrientationMask.all
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return self.orientationLock
}

struct AppUtility {
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }
}

添加到要强制定向的视图控制器中:

代码语言:javascript
复制
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    //let value = UIInterfaceOrientation.landscapeLeft.rawValue
    //UIDevice.current.setValue(value, forKey: "orientation")


    AppDelegate.AppUtility.lockOrientation(.landscapeLeft)

}
票数 11
EN

Stack Overflow用户

发布于 2018-08-16 07:15:23

对我来说,投票结果无效。相反,

代码语言:javascript
复制
override open var shouldAutorotate: Bool {
    return false
}

override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIApplication.shared.statusBarOrientation
}

这些密码有效。在Swift 4确认。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40413567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档