第二个UITouch事件触发第一个UITouch事件为什么?

时间:2010-08-07 14:36:34

标签: iphone

自从过去2天以来,我遇到了一个很大的问题。我正在使用多个启用Touch的视图。我的UIViewController有8-10个imageview。我想分别检测每个视图上的触摸,但一次检测多个视图。在所有图像视图上都检测到触摸,但问题在于 -

假设我点击图像视图并按住此图像视图,然后点击另一个图像视图,第二个图像视图检测到触摸成功,但它也会触发先前触摸并按住的第一个图像视图。但我不想要它。所以请任何人帮助我。代码级帮助表示赞赏。

NB。我的UIViewController还实现了用于滑动的TouchesMoved方法。

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for(UITouch *touch in event.allTouches) {
        if(CGRectContainsPoint([imView1 frame], [touch locationInView:self.view])){ 
            NSLog(@"imView 1 touched");
        }
        if(CGRectContainsPoint([imView2 frame], [touch locationInView:self.view])){ 
            NSLog(@"imView 2 touched");
        }
    }
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    for(UITouch *touch in event.allTouches) {
        if(CGRectContainsPoint([imView1 frame], [touch locationInView:self.view])){ 
            NSLog(@"imView 1 touch moved");
        }
        if(CGRectContainsPoint([imView2 frame], [touch locationInView:self.view])){ 
            NSLog(@"imView 2 touch moved");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试继承UIImageView并处理该子类中的touches代码。如果由于某种原因需要将触摸传递给父母,则可以处理触摸,然后将其发送给父视图,即父级视图控制器。

编辑:

拥有这样的自定义类

@interface CustomImageView : UIImageView {}@end
@implementation CustomImageView
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touch began %d",self.tag);
    [self.nextResponder touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touch moved %d",self.tag);
    [self.nextResponder touchesMoved:touches withEvent:event];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touch ended %d",self.tag);
    [self.nextResponder touchesEnded:touches withEvent:event];
}
@end

并且你的parrent代码是这样的

@implementation trashmeTouchIpadViewController
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"parent Touch Began");
        //do parent stuff
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"parent Touch ended");
        //do parent stuff
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setMultipleTouchEnabled:YES];
    UIImage *i1 = [UIImage imageNamed:@"img1.jpg"];
    CustomImageView *v1 = [[CustomImageView alloc] initWithImage:i1];
    v1.frame = CGRectMake(100, 100, 200, 200);
    v1.userInteractionEnabled = YES;
    v1.multipleTouchEnabled = YES;
    v1.tag = 111;
    [self.view addSubview:v1];
    [v1 release];
    UIImage *i2 = [UIImage imageNamed:@"img2.jpg"];
    CustomImageView *v2 = [[CustomImageView alloc] initWithImage:i2];
    v2.frame = CGRectMake(500, 100, 200, 200);
    v2.userInteractionEnabled = YES;
    v2.multipleTouchEnabled = YES;
    v2.tag = 999;
    [self.view addSubview:v2];
    [v2 release];
}