所以我正在做自定义手势识别,我遇到了麻烦。我需要监控所有当前触摸,但touchesBegan
,touchesEnded
,touchesMoved
和touchesCancelled
都只能给我他们正在监控的触摸。我需要对所有触摸进行计算,无论它们是否受到监控。我做了一些研究,我已经看到了自己监控触摸的建议,但对我来说并不顺利。这是我的代码:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
[myTouches unionSet:touches];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *objects = [myTouches allObjects];
for (UITouch *touch in touches) {
for (UITouch *touch2 in objects) {
if (CGPointEqualToPoint([touch2 locationInView:self.view], [touch previousLocationInView:self.view])) {
[myTouches removeObject:touch2];
[myTouches addObject:touch];
}
}
}
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
[myTouches minusSet:touches];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[myTouches minusSet:touches];
NSArray *objects = [myTouches allObjects];
for (UITouch *touch in touches) {
for (UITouch *touch2 in objects) {
if (CGPointEqualToPoint([touch2 locationInView:self.view], [touch previousLocationInView:self.view])) {
[myTouches removeObject:touch2];
}
}
}
}
我想要的是:myTouches
应该是屏幕上所有触摸的准确表示。
我得到的是:myTouches
不断增长,尽管有时从事件中触及的内容被正确注册为与myTouches
中的触摸相同。我还做了一个测试,我在整数中计算了touchesBegan
中注册的触摸次数,并减去了touchesEnded
中注册的触摸,并且数字总是显示为正数,这意味着正在注册更多触摸比结束了。请帮忙!
答案 0 :(得分:1)
尝试使用UIApplication的子类来监控应用程序中的所有触摸。
@interface MyUIApplication : UIApplication
然后使用sendEvent
MyUIApplication
- (void)sendEvent:(UIEvent *)event {
[super sendEvent:event];
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
//To get phase of a touch
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan){
//Do the stuff
}
//also you can use UITouchPhaseMoved, UITouchPhaseEnded,
// UITouchPhaseCancelled and UITouchPhaseStationary
}
}
并且不要忘记在main
中添加该类 int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, NSStringFromClass([MyUIApplication class]), NSStringFromClass([AppDelegate class]));
}
}