Xcode: Disable rotation for a view in the ViewController.swift
Asked Answered
T

1

5

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
    }
Tallow answered 10/4, 2019 at 22:52 Comment(2)
Look like the answer here can do what you are looking for: #38969919Inland
I am not sure it is what I am looking for. If the device is rotated, the view doesn't rotate.Tallow
L
9

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.

Lothians answered 11/4, 2019 at 8:7 Comment(1)
Wow. Thank you so much for the example.Tallow

© 2022 - 2024 — McMap. All rights reserved.