objective-c - 检测 View 中的任何触摸(iPhone SDK)

标签 objective-c iphone

我目前正在使用...

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

检测滑动。我一切正常。唯一的问题是,如果用户触摸了某物(例如 UIButton 或某物),则 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 不会被调用。是否有类似 touchesBegan 的东西,但如果我触摸 View 上的任何地方,它就会起作用?

提前致谢, 大卫

最佳答案

触摸事件是这样传播的:

  1. 递归地发送 UIViews -hitTest:withEvent:,直到某些 UIView 确定触摸在其边界内而不是在任何启用用户交互的 subview 内。
  2. UIWindow 将 -touchesBegan:withEvent: 和 friend 发送到步骤 1 中返回的 UIView,忽略任何 View 层次结构。

换句话说,-hitTest:withEvent:用于确定触摸的目标 View ,之后目标 View 获取所有-touches...:withEvent: 消息。如果您需要拦截可能从 UIButton 开始的滑动手势,您将必须覆盖 -hitTest:withEvent: 以返回 self

但是这种方法有一个问题。一旦你这样做了,你的按钮将停止工作,因为它不会收到任何 -touches...:withEvent: 消息。除非您检测到滑动手势,否则您必须手动将触摸转发到 subview 。这是一个严重的问题,而且根本不能保证有效。这就是 UIGestureRecognizers 的用途。

另一种方法是子类化 UIWindow 并覆盖 -sendEvent:,这可能更适合您的情况。

无论如何,请务必阅读 Event Handling文件彻底。在其他可怕的警告中,它说:

The classes of the UIKit framework are not designed to receive touches that are not bound to them; in programmatic terms, this means that the view property of the UITouch object must hold a reference to the framework object in order for the touch to be handled.

关于objective-c - 检测 View 中的任何触摸(iPhone SDK),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2615829/

相关文章:

iphone - 如何使用 UIMarkupTextPrintFormatter 打印带有本地镜像的本地 html?

iphone - 如何命名应用商店图标?

objective-c - 单击表行时,Cocoa 绑定(bind) "Selection"不会更改

objective-c - 从 Swift 到 Objective C - updateCallDurationForVisibleCells

objective-c - NSKeyedArchiver 因 CLLocationCoordinate2D 结构而失败。为什么?

android - 二维码中的电话号码

ios - 使用延迟加载在 ScrollView 上加载图像

iphone - 为什么我的程序在 objc_msgSend() 期间在 _class_isInitialized() 中接收到 EXC_BAD_ACCESS?

ios - 时区问题 "ZE8",如何将NSDate转换为NSString

ios - 在 Objective-C iOS 中替换去电屏幕