user1480092 user1480092 - 1 year ago 122
Objective-C Question

UIImageView as button

I'm trying to make a UIImageView accept actions and fire them everytime it clicked on the UIImageVie, but i'm having hard time in getting it to work, please help me out

but here is what i'm doing:

[View setUserInteractionEnabled:YES];

[View addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];

- (void) myAction:(id)sender
NSLog(@"It works!");

Answer Source


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");


override func viewDidLoad() {

    let imageView: UIImageView = UIImageView(frame: CGRectMake(100.0, 100.0, 100.0, 100.0))
    imageView.image = UIImage(named: "image.png")
    imageView.userInteractionEnabled = true

    let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(BaseVC.singleTapping(_:)))
    singleTap.numberOfTapsRequired = 1;


func singleTapping(recognizer: UIGestureRecognizer) {
    print("image clicked")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download