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

Sunny, Lee
3 min readJan 12, 2018

--

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.

Tips:

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.

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 :]

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

--

--

Sunny, Lee

CMU Master of Software Engineering student who loves outdoor activities