Ios Swift 3-检查今天扩展中的方向
UIDevice.current.orientation在swift 3中不再工作 它总是返回未知 除了下面的代码,我没有找到其他方法来获得方向Ios Swift 3-检查今天扩展中的方向,ios,swift,Ios,Swift,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
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.current
在getOrientation
方法中检测UIDeviceOrientation
,您可以从通知中确定,然后在处理通知时传递信息:
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")
}
}
初始化类时,或在viewdiload(:)
中,如果要在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)
}
然后,每当设备旋转时,将调用设备旋转(方向:)
,并将当前设备的方向传递给方法。然后可以相应地处理方向更改 非常感谢Pierce,但我注意到您提出的两种方法在今天的扩展中都不起作用。这就是我使用UIScreen.main的原因。也许我是wrong@Fr埃德里克·达尔博-我将更新我的答案,希望能对您当前的情况有所帮助。@Fr埃德里克·达尔博-请查看我的更新答案,它应该能满足您的需要,并且能够使用UIDevice
非常感谢您Pierce。我刚试过你提出的方法,但不幸的是,它不起作用。扩展的viewController从未收到通知。如果我从纵向模式打开“今日”分机并切换到横向模式,分机将保持纵向模式。要在横向中打开今日扩展,我必须打开一个接受横向的应用程序,切换到横向模式并打开今日扩展。在我的例子中,视图被重新加载,并且从未被通知。