iosswiftuiviewcontrolleruidevice

Get the current device orientation


I know that this question was asked before and tried to implement the suggested solution, but it doesn't work for me. Perhaps I am doing smth wrong. Do you have any idea?

Here is my code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var test: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    test.backgroundColor = UIColor.darkGray
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) // No need for semicolon

    func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            test.backgroundColor = UIColor.purple
        } else {
            test.backgroundColor = UIColor.blue
        }
      }
    }
 }

Solution

  • You have nested functions - that won't work. Change it to this:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated) // No need for semicolon
    }
    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        if UIDevice.current.orientation.isLandscape {
            test.backgroundColor = UIColor.purple
        } else {
            test.backgroundColor = UIColor.blue
        }
    }
    

    In fact, you can get rid of the override for viewWillLayoutSubviews with the code you've shown.