UIDevice.current.orientation在swift 3中不再起作用 它总是返回未知的
除了以下代码
之外,我没有找到其他方法来获取方向func isLandscape() -> Bool{
let scale = UIScreen.main.scale
let nativeSize = UIScreen.main.currentMode?.size
let sizeInPoints = UIScreen.main.bounds.size
if scale * sizeInPoints.width == nativeSize?.width{
return false
}else{
return true
}
}
见 What is the best way to detect orientation in an app extension?
答案 0 :(得分:0)
编辑:FrédéricDalBo希望能够将当前设备的方向传递到getOrientation
方法,因为他无法在他正在使用的扩展名内调用UIDevice.current
。希望这会有效,而不是使用UIDeviceOrientation
检测getOrientation
方法中的UIDevice.current
,您可以从Notification
确定,然后在处理通知时,通过沿着信息:
func getOrientation(orientation: UIDeviceOrientation) {
switch orientation {
case .portrait:
print("Portrait")
case .landscapeLeft:
print("Lanscape Left")
case .landscapeRight:
print("Landscape Right")
case .portraitUpsideDown:
print("Portrait Upside Down")
case .faceUp:
print("Face up")
case .faceDown:
print("Face Down")
case .unknown:
print("Unknown")
}
}
初始化课程时,或viewDidLoad(_:)
如果您想要处理ViewController
中的更改:
NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
func deviceRotated(_ notification: Notification) {
let device = notification.object as! UIDevice
let orientation = device.orientation
getOrientation(orientation: orientation)
}
然后,只要设备旋转,就会调用deviceRotated(orientation:)
,它会将当前设备的方向传递给方法。然后,您可以相应地处理方向更改。