lock orientation of a viewController in swift
Asked Answered
I

3

6

I'm a newbie in Swift and i have a problem locking the orientation to portrait in a viewController. Actually i have locked it using this code in my Custom Navigation Controller

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if (self.visibleViewController is ViewController)
    {
        return UIInterfaceOrientationMask.Portrait
    }
    return .All
}

Everything works fine and the ViewController is locked to portrait.The problem is when return to this controller from another in landscape mode. if i return to ViewController (pressing back from the NextViewController) in landscape then the ViewController appeared in landscape. Any suggestion?

Interment answered 15/5, 2016 at 16:52 Comment(1)
https://mcmap.net/q/265497/-how-do-i-programmatically-set-device-orientation-in-ios-7 In view did apprear, change the orientation.Dorset
S
8

In swift 3 this solution works

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if self.window?.rootViewController?.presentedViewController is LockedViewController {
        return UIInterfaceOrientationMask.portrait
    } else {
        return UIInterfaceOrientationMask.all
    }
}

Change LockedViewController to match the controller you would like locked.

Sitter answered 15/4, 2017 at 20:17 Comment(1)
Wow. This was exactly what I was looking for. Thank you so much for posting this!!Cacuminal
W
0

You can override the methods below

 override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait
  }
  override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    return UIInterfaceOrientation.Portrait
  }

Then, in your viewDidLoad, force the orientation by adding the code below

UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")
Winny answered 16/5, 2016 at 5:11 Comment(1)
thank's for your reply. The missing code was UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") but it works better on viewWillAppear.Interment
E
0

For swift3.0

To restrict different orientations for different views You need to do following things :

In App delegate File :

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {

        if self.window?.rootViewController?.presentedViewController is OtherViewController {

            return UIInterfaceOrientationMask.All;

        } else {
            return UIInterfaceOrientationMask.Portrait;
        }

    }
Ezekiel answered 3/3, 2017 at 23:50 Comment(1)
Does this not work in Swift 4? Can't get it too work.Rakehell

© 2022 - 2024 — McMap. All rights reserved.