首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS: UIDeviceOrientation没有按预期工作

iOS: UIDeviceOrientation没有按预期工作
EN

Stack Overflow用户
提问于 2020-10-26 15:09:01
回答 1查看 292关注 0票数 0

我一直在使用UIDeviceOrientation检查设备的物理方向。文档指出,这个方向不依赖于接口方向,生成的通知无论如何都会触发。

下面的示例代码可以在禁用定向锁定的设备上正常工作。但是当定向锁定被激活时,它就不能工作了。每次设备旋转或抖动时,示例代码都会打印UIDeviceOrientation.rawValue。

代码语言:javascript
复制
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)")
    }

}

如您所见,当方向锁定被激活时,通知不会被触发,甚至摇动设备时的原始值也是错误的。

我是漏掉了什么还是这是个虫子?

定位锁定:这意味着从苹果控制中心的功能,以实施所有应用程序的纵向模式。

EN

回答 1

Stack Overflow用户

发布于 2020-10-26 15:21:23

,我是错过了什么,还是这是个bug?

你不可能说出你知道什么,或者你“错过什么”,但这绝不是一个错误。从应用程序所处环境的角度来看,如果定位锁是打开的,设备就不能采用新的方向,因此通知不会启动。我想说,这确实是按照预期工作的,因此问题的标题是错误的(除非,您的意思是它不像您想要的那样工作!)

如果这对你来说很重要,那就是通过它来了解设备在太空中的物理位置,这就是核心运动的意义所在。有了它,你就可以探测到重力相对于设备的方向,这反过来会告诉设备在更大的物理意义上是如何定向的。

还值得注意的是,您不能依赖抖动编辑功能作为信号,因为用户可以轻松地将其关闭(例如,在我的手机上)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64539791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档