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.
}
}
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.
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.
I believe you need to enable user interaction on a UIImageView. Its set to false by default. Try:
tapView.userInteractionEnabled = true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With