Jeremy L
Jeremy L

Reputation: 3810

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

It is easy that we create an Action for a UIButton, we just Ctrl drag the button on the canvas in Interface Builder to the @implementation part of our code (in the Assistant Editor).

But what about a UIImageView? I want to say, if the user taps on this image (which is actually a good looking icon), then do something, but how can the Action be added because Ctrl drag doesn't do anything?

Upvotes: 3

Views: 4602

Answers (3)

Rob
Rob

Reputation: 437372

Alternatively, you can actually use a UIButton and set its image just like you would for an UIImageView. No need for manually writing gesture handlers on an UIImageView.

Upvotes: 1

Warif Akhand Rishi
Warif Akhand Rishi

Reputation: 24248

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




-(void)actionHandleTapOnImageView
{
NSLog(@"actionHandleTapOnImageView");
}

Upvotes: 8

melsam
melsam

Reputation: 4977

You need to handle the touchesBegan message in the UIImageView's parent UIViewController.

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

Also, make sure the UIImageView's "User Interaction Enabled" property is true.

Upvotes: 2

Related Questions