For iOS and Xcode, can we create an Action for a UIImageView object?

It’s easy to create an Action for UIButton, just Ctrldrag the button on the canvas in the Interface Builder to part of @implementationour code (in the assistant editor).

But what about UIImageView? I want to say if the user clicks on this image (this is actually a good icon), then there’s something to do, but how can I add an action because Ctrldrag does nothing?

+3
source share
3 answers
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] 
                                     initWithTarget:self 
                                     action:@selector(actionHandleTapOnImageView)];
[singleTap setNumberOfTapsRequired:1];
originalImageView.userInteractionEnabled = YES;
[originalImageView addGestureRecognizer:singleTap];
[singleTap release];




-(void)actionHandleTapOnImageView
{
NSLog(@"actionHandleTapOnImageView");
}
+8
source

You need to handle the touchsBegan message in the parent UIViewController UIImageView.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    
    UITouch *touch = [touches anyObject];
    if ([touch view] == myImageView) {
        [self handleTapOnImageView];  // <-- Handle it!
    }
}

Also, verify that the UIImageView "User Interaction Enabled" property is true.

+2

Alternatively, you can use UIButton and set its image in the same way as for UIImageView. There is no need to manually record gesture handlers in UIImageView.

+1
source

All Articles