I am working on a swift app for iPhone. There is a modal view in my application that I want only to be in portrait view.
My question is, how do I programmatically force the phone to not allow rotation? In other words, I am looking for code that will not allow a modal view to be displayed in landscape mode (turning on portrait rotation lock).
This is just for 1 modal view, so I can't turn off rotation for the entire app, otherwise I would just disable rotation altogether.
I found code in my research here But it is in objective C, in case that helps. Thanks!
Historically, if you wanted to restrict your iOS app to specific device orientations, you would check or uncheck the various “Device Orientation” options in your project settings. You can find these by selecting your Xcode Project > App Target > “General” tab. Xcode project "Device Orientation" options.
Swipe down from the top-right corner of your screen to open Control Center. Tap the Portrait Orientation Lock button to make sure that it's off. Turn your iPhone sideways.
Hi for LandscapeLeft and LandscapeRight (Update Swift 2.0)
And you have this in info
And UIController
override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return [UIInterfaceOrientationMask.LandscapeLeft,UIInterfaceOrientationMask.LandscapeRight] }
For PortraitUpsideDown and Portrait use that
override func shouldAutorotate() -> Bool { if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft || UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight || UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) { return false } else { return true } } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return [UIInterfaceOrientationMask.Portrait ,UIInterfaceOrientationMask.PortraitUpsideDown] }
Message from France, Merry Christmas !
Edit :
Other solution :
extension UINavigationController { public override func shouldAutorotate() -> Bool { if visibleViewController is MyViewController { return true // rotation } else { return false // no rotation } } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return (visibleViewController?.supportedInterfaceOrientations())! } }
You can paste these methods in the ViewController of each view that needs to be portrait:
override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With