Swift 100 Days: Project 24 - How To Rotate Only One ViewController to Landscape Orientation?

Sunny, Lee
Jan 12, 2018 · 3 min read
Image for post
Image for post

Environment: Swift 4 / Day: 88 / Date: Jan. 12, 2018 / Time: 6 hours

What I’ve learned:

・Rotate is freakin stupid in swift right now. why? 👇
・Because if there are tab bars or nav bars embed to the specific view controller you plan to rotate, then there’s no simple way, like simply calling a function, to allow rotating it.
・If you have only one view controller with no tab bar or nav bar, which is totally unrealistic in real project 😞, you can use the ‘shouldAutorotate’ override variable to true/false depending allowing rotate or not.


If you planned to do rotation in only one view controller like I did, you might started googling and found the resource below:

It’s a great article with only one big problem: COMPLETELY OUTDATED!!! It’s written in Swift 2.3 as I recalled, and outdated codes are pretty much unusable.

So here’s a translation of Swift 4 version:

👊 Heads-up 👊 : In the below example, the app only allows “Portrait” in all viewcontrollers except for one allowing “allButUpsideDown”. Make sure that your app also fits this situation or transfer the codes a bit to meet the circumstances.

OK then! Let’s start digging!

1. First of all, you need to make sure “Device Orientation” looks like this, which means only ‘Portrait’ mode is checked.

Image for post
Image for post

2. Add these two functions to AppDelegate, which helps you deal with embed in nav bar/tab bar situation mentioned above:

3. Finally, go to the specific view controller you planned to allow rotate and insert two parts of codes.

(1) viewWillDisappear: Here, we make sure the app goes back to the portrait mode after leaving the viewcontroller.

(2) Call the canRotate(): It is based on the functions we implemented in AppDelegate. Fortunately, they have smartly handle the rest of the problem for us. We just need to simply call this function in this specific viewcontroller.

  @objc func canRotate() -> Void {}

BOOM!!! That’s it! Three simple steps!

If you have any question, feel free to leave a comment. If you think this article is helpful, please give me a clap or multiple claps :]

Image for post
Image for post

Source: How to Rotate Only One View Controller to Landscape Orientation in iOS Swift

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store