简体   繁体   中英

Force Landscape orientation, Swift

I have a view controller that is designed in portrait view. I have another view controller designed in Landscape view (in storyboards). On my first view controller (portrait VC) i have a button that takes you to the landscape VC. When you click on the button the Landscape view controller shows up in portrait view initially and doesn't change until rotated. I would like to have this landscape view controller automatically show up in landscape without having to rotate it. Ive been coding this in swift, and have had no luck. In my plist menus i have all orientations enabled. Any help would be great.

You should add this in the second viewcontroller (designed to be in landscape) in the viewDidLoad

It is in swift3 :

let value =  UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

Hope it will help you :)

I'm working on a similar scenario I want to load and keep my first ViewController in Landscape orientation while allowing subviews to switch as needed

I think placing

override func viewDidLoad() {
    super.viewDidLoad()
    let value = UIInterfaceOrientation.LandscapeLeft.rawValue
    UIDevice.currentDevice().setValue(value, forKey: "orientation")
}

Swift 4

 override func viewDidLoad() {
        super.viewDidLoad()
        let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
    }

should load your view in landscape mode...But if holding phone in portrait orientation it will soon rotate...and that's the part I'm at...How to prevent the rotation.

I believe the best and most robust way to achieve this is by overriding two attributes - and avoid force orientation changes of the windows (as suggested by others).

This is how I got one of my view controllers to always show up in landscape mode, and stay there, without affecting the entire navigation stack. Add both of these overrides to the landscape view controller:

override var shouldAutorotate: Bool {
    false
}

This will prevent the view controller from auto-rotating when device orientation changes. Now that the view controller no longer rotates by itself, all you need to do is request the orientation you want:

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    UIInterfaceOrientation.landscapeLeft
}

And voila! Should do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM