Swift 3-在今天的扩展中检查方向



UIDevice.current.方向在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
}
}

参见在应用程序扩展中检测方向的最佳方法是什么?

编辑:Frédéric Dal Bo希望能够将当前设备的方向传递到getOrientation方法中,因为他无法在所使用的扩展中调用UIDevice.current。希望这能起作用,而不是使用UIDevice.currentgetOrientation方法中检测UIDeviceOrientation,您可以从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:),并将当前设备的方向传递到方法中。然后可以相应地处理方向更改。

最新更新