4

I am learning to program views in Xcode instead of using the .storyboard.

I do not want the view to rotate whenever it is being rotated.

I have this so far.

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white

        let imageView = UIImageView(image: #imageLiteral(resourceName: "facebook_logo.png"))
        view.addSubview(imageView)


        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 300).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    }
Miguel Yurivilca
  • 375
  • 5
  • 12
  • 2
    Look like the answer here can do what you are looking for: https://stackoverflow.com/questions/38969419/ios-how-to-enable-and-disable-rotation-on-each-uiviewcontroller/52221671 – oaccamsrazor Apr 10 '19 at 23:02
  • I am not sure it is what I am looking for. If the device is rotated, the view doesn't rotate. – Miguel Yurivilca Apr 10 '19 at 23:23

1 Answers1

8

I think the link provided by @oaccamsrazer above is the one you would need. To help out, I've implemented a small example project.

There are two view controllers, linked by a segue (and both wrapped in a UINavigationController).

In the AppDelegate you need the following:

var restrictRotation:UIInterfaceOrientationMask = .all

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask
{
    return self.restrictRotation
}

enter image description here

And viewWillAppear (since it is called when we traverse through the stack, so is better than using viewDidLoad) we

override func viewWillAppear(_ animated: Bool) {
    (UIApplication.shared.delegate as! AppDelegate).restrictRotation = .all
}

The second view will NOT rotate. It just features a label. enter image description here

in viewDidLoad (you could also use viewWillAppear)

override func viewDidLoad() {
    super.viewDidLoad()
    (UIApplication.shared.delegate as! AppDelegate).restrictRotation = .portrait
}

Using the storyboard or code only makes no difference, the implementation will still be the same.

stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47