UIImageView as button

All you have to do is drag a Tap Gesture Recognizer onto the imageView (in Storyboard) and enable User Interaction on the Attributes Inspector. If you want to use the image as a link to another view controller, just control-drag the Tap Gesture Recognizer icon in the bottom of the view controller to the destination view controller.


UIImageView is not a control, you can't add a target for control events to it. You have several options:

Place an invisible UIButton over the UIImageView and add your target to that. You can set the button's style to custom and its text (and image) to nothing to make it invisible.

Use just a UIButton. You can add a background image to it.

Add a UITapGestureRecognizer to your image view and implement it's touch handler method.

Subclass UIImageView and override the touch handling methods to do what ever you need to do.


UIImageView is not a UIControl so it doesn't have the addTarget:action:forControlEvents method as part of its interface. You can use a gesture recognizer instead.


Objective-C

In your viewDidLoad: method write this:

-(void)viewDidLoad {

    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(100.0, 100.0, 100.0, 100.0)];
    [imageview setImage:[UIImage imageNamed:@"image.png"]];
    [imageview setUserInteractionEnabled:YES];

    UITapGestureRecognizer *singleTap =  [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapping:)];
    [singleTap setNumberOfTapsRequired:1];
    [imageview addGestureRecognizer:singleTap];

    [self.view addSubview:imageview];
}

Then call your gesture method like this:

-(void)singleTapping:(UIGestureRecognizer *)recognizer {
    NSLog(@"image clicked");
}

Swift

override func viewDidLoad() {
    super.viewDidLoad()

    let imageView: UIImageView = UIImageView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0))
    imageView.image = UIImage(named: "image.png")
    imageView.isUserInteractionEnabled = true

    let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.singleTapping(recognizer:)))
    singleTap.numberOfTapsRequired = 1
    imageView.addGestureRecognizer(singleTap)

    self.view.addSubview(imageView)
}

@objc func singleTapping(recognizer: UIGestureRecognizer) {
    print("image clicked")
}