Search code examples
iosswiftxcode10.2

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


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
    }

Solution

  • 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.