How to detect orientation change?

2019-01-02 14:21发布

I am using Swift and I want to be able to load a UIViewController when I rotate to landscape, can anyone point me in the right direction?

I Can't find anything online and a little bit confused by the documentation.

20条回答
梦醉为红颜
2楼-- · 2019-01-02 15:23

I use UIUserInterfaceSizeClass to detect a orientation changed in a UIViewController class just like that:

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {

    let isiPadLandscapePortrait = newCollection.horizontalSizeClass == .regular && newCollection.verticalSizeClass == .regular
    let isiPhonePlustLandscape = newCollection.horizontalSizeClass == .regular && newCollection.verticalSizeClass == .compact
    let isiPhonePortrait = newCollection.horizontalSizeClass == .compact && newCollection.verticalSizeClass == .regular
    let isiPhoneLandscape = newCollection.horizontalSizeClass == .compact && newCollection.verticalSizeClass == .compact

     if isiPhonePortrait {
         // do something...
     }
}
查看更多
明月照影归
3楼-- · 2019-01-02 15:24

Full working implementation of how to detect orientation change in Swift 3.0.

I chose to use this implementation because phone orientations of face up and face down were important to me, and I wanted the view to change only once I knew the orientation was in the specified position.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //1
        NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

    }

    deinit {
        //3
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
    }

    func deviceOrientationDidChange() {
        //2
        switch UIDevice.current.orientation {
        case .faceDown:
            print("Face down")
        case .faceUp:
            print("Face up")
        case .unknown:
            print("Unknown")
        case .landscapeLeft:
            print("Landscape left")
        case .landscapeRight:
            print("Landscape right")
        case .portrait:
            print("Portrait")
        case .portraitUpsideDown:
            print("Portrait upside down")
        }
    }

}

The important pieces to note are:

  1. You listen to the DeviceOrientationDidChange notification stream and tie it to the function deviceOrientationDidChange
  2. You then switch on the device orientation, be sure to take notice that there is an unknown orientation at times.
  3. Like any notification, before the viewController is deinitialized, make sure to stop observing the notification stream.

Hope someone finds this helpful.

查看更多
登录 后发表回答