Evan Zimmerman
Evan Zimmerman

Reputation: 353

Locking orientation on UIViewController for specific view controllers in Swift

I have a user setting in my application which is supposed to set the orientation of specific view controllers to either landscape or portrait. The user presses a button on the main screen to toggle landscape/portrait for the other view controllers in the app by setting a global variable which should be read by the other controllers.

I have extended the UINavigationController as follows:

extension UINavigationController {
  public override func supportedInterfaceOrientations() -> Int {
    return visibleViewController.supportedInterfaceOrientations()
  }
}

I have also tried changing the visibleViewController to topViewController with no luck.

In all of my UIViewController files I then override the function:

override func supportedInterfaceOrientations() -> Int {
  return appOrientation // global user setting
}

The problem is that the only view controller that ever gets this function called is the main view controller (the first view the user sees and where the user can select the orientation). Why does this function not get called in the subsequently pushed view controllers?

The global appOrientation variable is set to either of the following when the user toggles it:

let orientationPortrait = Int(UIInterfaceOrientationMask.Portrait.rawValue | UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
let orientationLandscape = Int(UIInterfaceOrientationMask.Landscape.rawValue)

If I return one of these defines in the main view controller's supportedInterfaceOrientation function, the entire app is oriented to the define (not what I want).

I must be missing something here.

Upvotes: 1

Views: 1057

Answers (1)

Dom Bryan
Dom Bryan

Reputation: 1268

I think I have a solution for you. I don't know whether I got the full grasp of the question but I set a button on the main view (this is to simulate your settings page) I made a variable called presses, when the button was pressed, 1 was added to presses, when the button was pressed again, 1 was subtracted from presses. (I also changed the name of the button when it is pressed because I'm OCD like that).

Then on the next view I made an if statement in the viewwillappear function. I asked if presses was equal to one, set the orientation landscape and if presses equals 2, then set orientation to portrait. I added a nav bar in so you can go back and forth trying both orientations. I made sure to set the orientation of the main view to portrait because you set the entire device orientation, so if you were to simply go forward and the new view be landscape, then when you come back the main view will also be landscape.

Anyway I have built a quick project for you and here is the GitHub link for you: https://github.com/dombryan94/SetOrientationOfOtherViews

Let me know if this is what you are looking for, I hope this helps!

Upvotes: 1

Related Questions