Determine Device Orientation in Swift

In this short Swift code example, you will learn how to determine device orientation in Swift.

  • Determine device orientation when the view is about to appear
  • Determine device orientation when device is being rotated to Landscape or Portrait
import UIKit
class ViewController: UIViewController {
    var textView:UITextView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
 
        determineMyDeviceOrientation()
    }
    
    func determineMyDeviceOrientation()
    {
        if UIDevice.current.orientation.isLandscape {
            print("Device is in landscape mode")
        } else {
            print("Device is in portrait mode")
        }
    }
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        
        determineMyDeviceOrientation()
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
 
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published.