在视图中检测任何触摸(iPhone SDK) [英] Detect ANY touch in a view (iPhone SDK)
问题描述
我当前正在使用...
I'm currently using ...
- (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之类的东西,但是如果我在视图上触摸任何地方都可以使用?
to detect swipes. I've got everything working. The only problem is if the user touches on top of something (eg a UIButton or something) the - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
is not called. Is there something like touchesBegan but will work if I touch ANYWHERE on the view?
预先感谢, 大卫
推荐答案
触摸事件的传播方式如下:
Touch events propagate like this:
- UIViews递归发送 -hitTest:withEvent:,直到某些UIView确定触摸在其边界之内,而不在任何启用用户交互的子视图之内.
- UIWindow将 -touchesBegan:withEvent:和朋友发送到步骤1中返回的UIView,而忽略任何视图层次结构.
- UIViews get sent -hitTest:withEvent: recursively until some UIView decides that the touch is inside its bounds and not inside any user-interaction-enabled subview.
- UIWindow sends -touchesBegan:withEvent: and friends to the UIView returned in step 1, ignoring any view hierarchy.
换句话说, -hitTest:withEvent:用于确定触摸的目标视图,此后,目标视图将获得所有 -touches ...:withEvent:消息.如果需要截取可能从UIButton开始的滑动手势,则必须重写 -hitTest:withEvent:以返回 self .
In other words, -hitTest:withEvent: is used to determine the target view for the touch, after which the target view gets all -touches...:withEvent: messages. If you need to intercept the swipe gesture which may begin in a UIButton, you will have to override -hitTest:withEvent: to return self.
但是这种方法存在问题.完成此操作后,您的按钮将停止工作,因为它不会收到任何 -touches ...:withEvent:消息.除非您检测到滑动手势,否则您将必须手动将触摸转发到子视图.那是臀部的严重痛苦,根本无法保证它能正常工作.这就是UIGestureRecognizers的目的.
But there's a problem with this approach. Once you do that, your button will stop working because it won't get any -touches...:withEvent: messages. You will have to forward touches to subviews manually unless you detect a swipe gesture. That is a serious pain in the butt and is not guaranteed to work at all. That's what UIGestureRecognizers are for.
另一种方法是将UIWindow子类化并覆盖 -sendEvent:,这在您的情况下可能会更好.
Another approach is to subclass UIWindow and override -sendEvent:, which may work better in your case.
无论如何,请确保您已阅读事件处理一个>文件.除其他可怕的警告外,它还说:
Anyway, make sure you read the Event Handling documentation thoroughly. Among other scary warnings it says:
UIKit框架的类是 并非旨在接收 不受他们约束;在程序化中 术语,这意味着视图 UITouch对象的属性必须 引用框架 为了使触摸成为对象 处理.
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.
这篇关于在视图中检测任何触摸(iPhone SDK)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!