Search code examples
objective-cuiimageviewuitouch

how can i detect Custom UIImageView touch event?


i am using custom UIImageview for detect touch? but i am unable to detect touch on that particular imageview.

-(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"];
   }
 }

In this code i am not detect touch? pls help me?

with out custom view's it's detected.


Solution

  • You need to enable user interaction for UIImageViews you want to interact with.

    @property(nonatomic, getter=isUserInteractionEnabled) BOOL userInteractionEnabled

    something like that:

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

    otherwise the images will not get touches...