views:

23

answers:

1

I've got a set of Images and would like to know which I have touched. How could I implement that ? To be more precise: A "Home-Class" will instantiate a couple of Image-Classes:

Image *myImageView = [[Image alloc] initWithImage:myImage];

The image-class looks something like this:

- (id) initWithImage: (UIImage *) anImage 
  {

     if ((self = [super initWithImage:anImage])) 
     {
     self.userInteractionEnabled = YES;
     }
     return self;
  }
}

later on, I use these touches-event-methods also in the Image-class:

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

My problem at the moment: the touchesBegan/Ended methods will be fired no matter where I touched the screen, but I would like to find out which of the Images has been touched...

A: 

Whenever you get the touch, you check if that touch happen in between your image area. Here is the example code, lets suppose you have UIImage object called img.

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];

    CGPoint location = [touch locationInView:self.view];

    if (location.x >= img.x && location.x <= img.x && location.y >= img.y && location.y <= img.y)
    {
        // your code here...
    }


}
itsaboutcode