Getting device orientation in Swift

后端 未结 13 1455
滥情空心
滥情空心 2020-11-28 23:23

I was wondering how I can get the current device orientation in Swift? I know there are examples for Objective-C, however I haven\'t been able to get it working in Swift.

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 23:50

    I had issues with using InterfaceOrientation, it worked OK except it wasn't accessing the orientation on loading. So I tried this and it's a keeper. This works because the bounds.width is always in reference to the current orientation as opposed to nativeBounds.width which is absolute.

        if UIScreen.mainScreen().bounds.height > UIScreen.mainScreen().bounds.width {
            // do your portrait stuff
        } else {    // in landscape
            // do your landscape stuff
        }
    

    I call this from willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) and from viewDidLoad but it flexible.

    Thanks to zSprawl for the pointer in that direction. I should point out that this is only good for iOS 8 and later.

提交回复
热议问题