Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a tap gesture to an image with swift

Tags:

ios

swift

I know this is quite basic, I'm starting out with swift and I couldn't find a working example.

I'd like to tap an image and do an action. The IBOutlet is linked to an image on the Main Storyboard. When I tap it, I get nothing. I was expecting to get a console message. What am I doing wrong?

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var tapView: UIImageView!
    let tapRec = UITapGestureRecognizer()

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

        tapRec.addTarget(self, action: "tappedView")
        tapView.addGestureRecognizer(tapRec)

    }

    func tappedView(){
        println("image tapped")
    }

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


}
like image 785
jackreichert Avatar asked Nov 11 '14 19:11

jackreichert


People also ask

How do you make a clickable view in Swift?

The only possible way to add a click event on UIView is using UITapGestureRecognizer . You can either add an UITapGestureRecognizer using interface builder or you can do it programmatically. This way is a bit inefficient as we need to add one function for each view which will be clickable.

How do I add actions to UIImageView?

Open the Library, look for "Tap Gesture Recognizer" object. Drag the object to your storyboard, and set the delegate to the image you want to trigger actions. Then go to the view controller, drag the same object to set the IBAction.


1 Answers

I believe you need to enable user interaction on a UIImageView. Its set to false by default. Try:

tapView.userInteractionEnabled = true;
like image 176
Joel Bell Avatar answered Oct 03 '22 01:10

Joel Bell