Swift - How to detect orientation changes

后端 未结 13 1829
余生分开走
余生分开走 2020-11-29 19:49

I want to add two images to single image view (i.e for landscape one image and for portrait another image)but i don\'t know how to detect orientation changes using swift lan

13条回答
  •  悲&欢浪女
    2020-11-29 20:36

    Using NotificationCenter and UIDevice's beginGeneratingDeviceOrientationNotifications

    Swift 4.2+

    override func viewDidLoad() {
        super.viewDidLoad()        
    
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
    }
    
    deinit {
       NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)         
    }
    
    func rotated() {
        if UIDevice.current.orientation.isLandscape {
            print("Landscape")
        } else {
            print("Portrait")
        }
    }
    

    Swift 3

    override func viewDidLoad() {
        super.viewDidLoad()        
    
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
    }
    
    deinit {
         NotificationCenter.default.removeObserver(self)
    }
    
    func rotated() {
        if UIDevice.current.orientation.isLandscape {
            print("Landscape")
        } else {
            print("Portrait")
        }
    }
    

提交回复
热议问题