2016-11-04 65 views
11

我試圖防止一個UIViewController旋轉,我不能實現這一點。重寫shouldAutorotate不工作在斯威夫特3

我在做這樣的事情:

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中做的事情?

+1

你的'supportedInterfaceOrientations'是什麼樣的? – matt

+0

@matt我編輯的問題添加, – pableiros

+0

謝謝。好的,如果這是一個呈現的視圖控制器,它應該只出現在肖像中並留在那裏。如果沒有發生,那麼故事中就必須有更多的東西。你能描述一下這個視圖控制器是怎麼呈現的嗎?向我證明這是一個全屏頂級的視圖控制器。 – matt

回答

22

我不知道爲什麼要投票結束這個問題,如果我可以重現這種行爲很多次。 UIViewController位於模塊打開的UINavigationController內。

這是我所做的解決問題。

我創建這個類,我設置爲UINavigationController是containt,我想阻止UIViewController旋轉

class NavigationController: UINavigationController { 

    override var shouldAutorotate: Bool { 
     return false 
    } 

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask { 
     return .portrait 
    } 

} 

而且多數民衆贊成它,它爲我工作

+0

但是如果您只想要特定的UIViewController不旋轉而不是整個導航堆棧?這個答案看起來像一個更好的:http://stackoverflow.com/a/39805665 –

+0

@RoyShilkrot這是可以的,問題的目標是如何防止一個視圖控制器內的一個導航控制器的旋轉,而不是如何防止整個導航堆棧中的特定視圖控制器 – pableiros

3

添加該代碼AppDelegate中。迅速

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") 
    } 
} 

添加到您要強制定向視圖 - 控制:

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    //let value = UIInterfaceOrientation.landscapeLeft.rawValue 
    //UIDevice.current.setValue(value, forKey: "orientation") 


    AppDelegate.AppUtility.lockOrientation(.landscapeLeft) 

} 
+0

這適用於我,但接受的答案更清晰並且也適用。有沒有一個具體的情況下,接受的答案是不可能的,只有這個作品? – paul