Trouble responding to a tap on an image view

81 Views Asked by At

Why is my UITapGestureRecognizer not triggering my function for a UIAlertAction? When I build and run my app for the iOS Simulator, my image will not recognize a tap to trigger the alert.

Any suggestions would be appreciated. Thanks, Swift friends!


import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let rect = CGRect(x:20,y:20,width:150,height:100)
    let imageView = UIImageView(frame:rect)

    let image = UIImage(named:"image.png")
    imageView.image = image

   // imageView.isUserInteractionEnabled = true
    self.view.addSubview(imageView)
    let guesture = UITapGestureRecognizer(target: self,action:
        #selector(ViewController.singleTap))
    imageView.addGestureRecognizer(guesture)
}


func singleTap()
{
    let alertView = UIAlertController(title: "Heading", message: "Message!", preferredStyle: .Alert)

    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alertView.addAction(defaultAction)

    self.presentViewController(alertView, animated: true, completion: nil)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
1

There are 1 best solutions below

0
On

Uncommenting this line in your code

// imageView.isUserInteractionEnabled = true.

might work. Add this also

image.multipleTouchEnabled = YES;
tap.numberOfTapsRequired = 1;