我应该在我的主视图中管理两个不同的视图;我想检测视图中手指的确切数量,也就是说,如果我在第一个视图中有四个手指,我想要一个var值= 4,如果我在第二个视图中有三个手指,我想要另一个var值= 3。我给你看我的代码不能正常工作。
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
NSLog(@"cgpoint:%f,%f", touchLocation.x, touchLocation.y);
if (CGRectContainsPoint(view1.frame, touchLocation)){
NSLog(@"TOUCH VIEW 1");
totalTouch1 = [[event allTouches]count];
NSLog(@"TOTAL TOUCH 1:%d", totalTouch1);
}
else if (CGRectContainsPoint(view2.frame, touchLocation)){
NSLog(@"TOUCH VIEW 2");
totalTouch2 = [[event allTouches]count];
NSLog(@"TOTAL TOUCH 2:%d", totalTouch2);
}
}
在我的代码中,如果我开始把我的手指放在"first view"中,这没问题,但是如果我把我的第四个手指放在second view中我的代码输入第一个"if"并说我的手指还在first view中。我不明白这个问题。
[[event allTouches] anyObject];
只获取一个触摸。
你需要遍历所有的触摸,像这样:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
int touch1 = 0;
int touch2 = 0;
NSArray *touches = [[event allTouches] allObjects];
for( UITouch *touch in touches ) {
CGPoint touchLocation = [touch locationInView:self.view];
NSLog(@"cgpoint:%f,%f", touchLocation.x, touchLocation.y);
if (CGRectContainsPoint(view1.frame, touchLocation)){
NSLog(@"TOUCH VIEW 1");
touch1 += 1;
NSLog(@"TOTAL TOUCH 1:%d", totalTouch1);
}
else if (CGRectContainsPoint(view2.frame, touchLocation)){
NSLog(@"TOUCH VIEW 2");
touch2 += 1;
NSLog(@"TOTAL TOUCH 2:%d", totalTouch2);
}
}
NSLog(@"Total touches on view 1: %d", touch1);
NSLog(@"Total touches on view 2: %d", touch2);
}