ios - 获取 UIView 上的最后一个触摸事件

标签 ios objective-c uiview uievent

Note: This is a question similar to what is asked here, but the answer provided there is not exactly a solution in my case. The question's objective is different too. Reference: touchesBegan - Only needs the last touch action - iPhone

我正在尝试在 UIView 中处理多个触摸。我需要按顺序获得准确的触摸位置。

目前,我正在附加这样的选择器:

[myView addTarget:self action:@selector(touchBegan:withEvent:) forControlEvents: UIControlEventTouchDown];

这是我的处理程序,

- (void)touchBegan:(UIButton *)c withEvent:ev {
    UITouch *touch = [[ev allTouches] anyObject];

这里的问题是 [ev allTouches] 返回一个无序的 NSSet,所以我无法获得触摸事件的确切最后位置,以防多次触摸。

有没有办法在处理多个触摸的情况下获取最后一个位置?

最佳答案

您始终可以创建 View 的子类并覆盖 hitTest 以获得准确的触摸点

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    debugPrint(point)
    return super.hitTest(point, with: event)
}

这里只是记录接触点。只是为了展示它是如何工作的,我在我的 ViewController 中添加了 touchesBegan 并记录了触摸集中的第一个触摸点

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    debugPrint(touches.first)
}

这是两者的控制台日志

(175.66667175293, 175.33332824707)

Optional( phase: Began tap count: 1 force: 0.000 window: ; layer = > view: > location in window: {175.66665649414062, 175.33332824707031} previous location in window: {175.66665649414062, 175.33332824707031} location in view: {175.66665649414062, 175.33332824707031} previous location in view: {175.66665649414062, 175.33332824707031})

所以 HitTest 说,你的接触点是 (175.66667175293, 175.33332824707) 而 touches.first 说在 View 中的位置:{175.66665649414062, 175.33332824707031} 基本相同。

hitTest 可以用来替代 touchBegan 吗?没有

这就是为什么我在上面的评论中询问您到底想达到什么目的。如果您正在寻找对触摸的持续监控,touchBegantouchMovetouchEnd 是您应该选择的委托(delegate),但如果您正尝试监视单个触摸并找到它的确切触摸点,您可以随时使用 hitTest

希望对你有帮助

关于ios - 获取 UIView 上的最后一个触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51627118/

相关文章:

ios - Firebase - 在没有安全节点的情况下获取数据?

iphone - 当传递给 Objective-C 中的方法时,浮点值会发生变化

ios - 在两个 NSDate 之间减去 1 分钟

iphone - 如何使 uiview 保持在其他 View 之上

swift - 固定中心的动画 UILabel 宽度

ios - 可以拥有单例 UIView 子类吗?

ios - 如何在xcode中提交时触发自动缩进

ios - 如果当前在屏幕上不可见,是否可以获取 View Controller 的快照,包括其状态栏?

iOS NSMutablearray 释放行为

ios - 如何删除 iphone 中 tableView 单元格下方的行