Search code examples
iphoneiosuiimageviewuitouch

iOS : detect UIImageView for UITouch Events


I've added some UIImageView dynamically and filled it with different images, what I am trying to do is "Allow user to set position for any UIImageView", for that I used

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    //Here I want the object of particular UIImageView on which user touched.
}

In that method I'm doing,

NSLog(@"%@",[touches anyObject]);

It returns output

<UITouch: 0x68b95e0> phase: Began tap count: 1 window: <UIWindow: 0x68875d0; frame = (0 0; 320 480); layer = <UIWindowLayer: 0x68b6470>> view: <UIImageView: 0x6a74cf0; frame = (83.7763 83.7763; 182.447 182.447); transform = [0.968912, -0.247404, 0.247404, 0.968912, 0, 0]; alpha = 0.8; opaque = NO; tag = 3; layer = <CALayer: 0x6a74980>> location in window: {161, 230} previous location in window: {161, 230} location in view: {52.7761, 105.448} previous location in view: {52.7761, 105.448}

Note, in above output, it showing my UIImageView object on which I touched. But I want that object from it!!!

I want my UIImageView on which user touched?, I have already set property userInteractionEnabled=YES so the problem isn't with it!

I used below code to get it so, but it wont work.

NSInteger tag=[[[touches anyObject] view] tag]; //It only returns tag of UIView tag

I Google it but doesn't come with solution!

Thank you in advance for any help!


Solution

  • -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    {
        UITouch *touch=[touches anyObject];
    
        if([[touch valueForKey:@"view"] isKindOfClass:[UIImageView class]])
        {
                UIImageView *viewSelected=(UIImageView *)[touch valueForKey:@"view"]; //it returns touched object
                //for further differences can user viewSelected.tag
        }
    }