没有uigesturerecognizer的ios触摸位置

Posted

技术标签:

【中文标题】没有uigesturerecognizer的ios触摸位置【英文标题】:ios touch location without uigesturerecognizer 【发布时间】:2017-08-30 09:41:07 【问题描述】:

如何在没有 uigesturerecognizer 的情况下在 uiwindow 或 uiview 上获取触摸位置, 目的是以极低的延迟获取触摸位置,因为调度程序可以延迟触摸触发事件

【问题讨论】:

【参考方案1】:

您需要继承UIView 并覆盖UIResponderUIView 的超类)方法touchesBegan(_:with:)。有关方法here,请参阅文档。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
    if let touch = touches.first 
        // Get the touch location in THIS VIEW's coordinate system:
        let locationInThisView = touch.location(in: self)

        // Get the touch location in the WINDOW's coordinate system
        let locationInWindow = touch.location(in: nil)
    

另外,请确保您的视图将属性isUserInteractionEnabled 设置为true

【讨论】:

当我覆盖 touchesBegan 时,我仍然需要等到调度程序触发 touchesBegan 事件,在我的个人测试中,它以 50Hz 触发,有一些延迟,但我想获得 100Hz,低延迟 据我所知,ios SDK 没有提供更快的东西。也许如果您将UIWindow 子类化(视图层次结构的根对象),它会被调用得稍早一些? 也许覆盖UIApplication.sendEvent()?想不出别的了。无论哪种方式,touchesBegan(... 都足够快,以至于交互对人类用户来说是自然的。我想知道您的应用正在尝试做什么,需要在这种实时条件下检测点击。【参考方案2】:

在您的 UIView 子类中覆盖以下方法。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
    let point =  touches.first?.location(in: self)
    print("location: ", point ?? CGPoint.zero)

【讨论】:

当我覆盖 touchesBegan 时,我仍然需要等到调度程序触发 touchesBegan 事件,在我的个人测试中,它以 50Hz 触发,有一些延迟,但我想获得 100Hz,低延迟

以上是关于没有uigesturerecognizer的ios触摸位置的主要内容,如果未能解决你的问题,请参考以下文章

iOS 无限深度嵌套的 TableView/UIGestureRecognizer 视图树和 iPAD 需要 2 根手指在 tableview 上滚动

关于iOS的手势UIGestureRecognizer问题

在iOS中获取UIGestureRecognizer的Action

iOS:从 UIGestureRecognizer 崩溃的关键窗口子视图元素

iOS - UITableViewCell 中的 UIGestureRecognizer 类似于 Snapchat

使用 UIGestureRecognizer 传递奇怪的 ios 触摸事件