禁用UINavigationController和UIViewController在Swift 4中的屏幕方向

嗨我想停止在我的项目中的视图控制器之一的自动旋转。在下面的快照, 禁用UINavigationController和UIViewController在Swift 4中的屏幕方向

我有一个开始UINavigationController,然后UIViewController。我已经实现下面的代码以停止自转:

extension UINavigationController { 

override open var shouldAutorotate: Bool {

get {

return false

}

}

override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{

get {

return UIInterfaceOrientationMask.landscape

}

}}

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

override open var shouldAutorotate: Bool {

return false

}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask

{

return .landscape

}

}

但上面的代码似乎并没有打电话,没有服用任何影响。我正在使用Xcode 9swift 4.0。 任何建议,将不胜感激。

问候, NEENA

回答:

创建一个类并将其设置为UINavigationController,然后在你的故事板使用这个新的类/ XIB

在您的分机:

class NavigationController: UINavigationController {  

override var shouldAutorotate: Bool {

return topViewController?.shouldAutorotate ?? super.shouldAutorotate

}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {

return topViewController?.supportedInterfaceOrientations ?? super.supportedInterfaceOrientations

}

}

在你的控制器:

override var shouldAutorotate: Bool { 

return false

}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {

return .portrait

}

回答:

我是有同样的问题。我查看了所有堆栈溢出,并尝试了许多解决方案,但都没有工作。我在苹果开发者论坛上发现了这个解决方案,它的功能就像一个魅力。

我在这里添加他们的解决方案,希望其他人在未来能够更容易地找到,给author以及链接到their post。

添加到您的AppDelegate文件:

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)

AppDelegate.AppUtility.lockOrientation(.portrait)

}

override func viewWillDisappear(_ animated: Bool) {

super.viewWillDisappear(animated)

AppDelegate.AppUtility.lockOrientation(.all)

}

以上是 禁用UINavigationController和UIViewController在Swift 4中的屏幕方向 的全部内容, 来源链接: utcz.com/qa/263087.html

回到顶部