我如何检测自定义UIImageView触摸事件?

时间:2012-10-15 12:39:54

标签: objective-c uiimageview uitouch

我使用自定义UIImageview来检测触摸?但我无法检测到特定图像视图的触摸。

-(void)viewDidLoad {
  [super viewDidLoad];
  mainView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
  image = [[UIImageView alloc] initWithFrame:CGRectMake(10, 300, 100, 100)];
  image.image = [UIImage imageNamed:@"CyanSquare.png"];
  image2 = [[UIImageView alloc] initWithFrame:CGRectMake(150, 600, 100, 100)];
  image2.image = [UIImage imageNamed:@"CyanSquare.png"];
  image.tag = 1;
  image2.tag = 2;
  [self.mainView addSubview:image];
  [self.mainView addSubview:image2];
  [self.view addSubview:mainView];
}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

   UITouch *touch = [[event allTouches] anyObject];
   [super touchesBegan:touches withEvent:event];
   if ([touch view] == [image viewWithTag:1]) {
    NSLog(@"touch  beggin 1");
    mainView.image = [UIImage imageNamed:@"VideoBkGround.png"];
   }
   if ([touch view] == [image2 viewWithTag:2])
    {
    NSLog(@"touch  beggin 2");
    mainView.image = [UIImage imageNamed:@"VideoRunning.png"];
   }
 }

在这段代码中我没有检测到触摸?请帮助我?

没有自定义视图,它被检测到。

1 个答案:

答案 0 :(得分:1)

您需要为要与之交互的UIImageView启用用户交互。

@property(nonatomic, getter=isUserInteractionEnabled) BOOL userInteractionEnabled

类似的东西:

image.userInteractionEnabled = YES; 
image2.userInteractionEnabled = YES;

否则图像不会触及......