Swift -> Add tap gesture recognizer to views

There are two ways to add click event in swift, through storyboard or programmatically. Click depends on type of widgets. If it’s a UIButton, then it can be easily done through storyboard but if it is UILabel, UIView or even a UIImageView then you can implement click in code using UITapGestureRecognizer.

Let’s start with click implementation in StoryBoard.

  1. We have a ExampleView class which extends UIView. In the storyboard we have placed a button “ClickMe!”. Touch Up Inside and Touch Up Outside events help in linking the action for this button.(Shown in image 6.)

2. Next, we link our ExampleView class in the storyboard. Do note “User Interaction Enabled” checkbox as Checked.

3. Drag the event attribute on the screen to see associated button actions created in ExampleView class.

4. We have just one IBAction function (aClickMe) in class, thus it will appear on the storyboard.

5. As soon as you click it will get linked with event on right hand side.

6. Finally, our class which binds IBAction with button in our storyboard. There are other functions also which are important in this UIView extended class, but we are not focusing on them at the moment. The double circle on left of function shows that it got linked with our storyboard element.

But we are here to discuss UITapGestureRecognizer, so this class helps in associating a click/tap on all other widgets programmatically.

  1. This time let’s create an UIImageView. The image used is system defined Calendar image. We have created a ExampleViewController class extending UIViewController.

2. When you drag New referencing outlet on storyboard you will see our IBOutlet variable oCalendarImageView which we have created in our class.

3. Finally, the code. Here we have created a class which extends UIViewController. In viewDidLoad() we have associated the function openCalendar with UITapGestureRecognizer selector.

class ExampleViewController: UIViewController {
    @IBOutlet weak var oCalendarImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGestureCalendarImageView = UITapGestureRecognizer(target: self, action:  #selector (self.openCalendar (_:)))
         self.oCalendarImageView.addGestureRecognizer(tapGestureCalendarImageView)
    }

    @objc func openCalendar(_ sender:UITapGestureRecognizer){
        // Open Calendar
    }
    

Happy Coding! 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: