[英]iOS 7 supportedInterfaceOrientation not working as intended
[英]iOS: UIDeviceOrientation is not working as intended
我一直在使用 UIDeviceOrientation 來檢查設備的物理方向。 文檔指出此方向不依賴於界面方向,並且生成的通知無論如何都應該觸發。
下面的示例代碼在禁用了方向鎖定的設備上運行良好。 但是當激活方向鎖定時它將不起作用。 每次旋轉或搖動設備時,示例代碼都會打印 UIDeviceOrientation.rawValue。
class ViewController: UIViewController {
private static var backgroundColors: [UInt: UIColor] = [
0: .blue, 1: .red, 2: .green, 3: .yellow, 4: .purple, 5: .black, 6: .orange, 7: .white
]
private var colorIndex: UInt = 0
private var cancelToken: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.applicationSupportsShakeToEdit = true
// This does not make any difference since UIDevice.current.isGeneratingDeviceOrientationNotifications is always true anyways.
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
cancelToken = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification).sink { _ in
guard let nextColor = Self.backgroundColors[self.colorIndex % UInt(Self.backgroundColors.keys.count)] else {
fatalError("Index out of bounds.")
}
self.view.backgroundColor = nextColor
self.colorIndex += 1
print("Orientation: \(UIDevice.current.orientation.rawValue)")
}
}
deinit {
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
guard motion == .motionShake else { return }
print("Shake -> Orientation: \(UIDevice.current.orientation.rawValue)")
}
}
如您所見,當方向鎖定被激活時,通知不會被觸發,甚至搖動設備時的原始值也是錯誤的。
我錯過了什么還是這是一個錯誤?
方向鎖定:這意味着來自 Apples 控制中心的 function 為所有應用程序強制使用縱向模式。
我錯過了什么還是這是一個錯誤?
不可能說出您知道什么或“錯過”什么,但這幾乎不是錯誤。 從應用程序所在環境的角度來看,如果方向鎖定打開,設備無法采用新的方向,因此不會觸發通知。 我會說這確實按預期工作,所以問題的標題是錯誤的(除非,也許,你的意思是它沒有按你的預期工作。)。
如果了解設備在空間中的物理位置對您來說很重要,那么這就是 Core Motion 的目的。 有了它,你可以檢測到重力相對於設備的方向,這反過來會告訴你設備在更大的物理意義上是如何定向的。
還值得注意的是,您不能依賴搖動編輯功能作為信號,因為用戶可以輕松將其關閉(例如,它在我的手機上處於關閉狀態)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.