我目前正在使用...
- (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 上的任何地方,它就会起作用?
提前致谢, 大卫
最佳答案
触摸事件是这样传播的:
- 递归地发送 UIViews -hitTest:withEvent:,直到某些 UIView 确定触摸在其边界内而不是在任何启用用户交互的 subview 内。
- 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/