Search code examples
iosuiviewswift4uitapgesturerecognizer

Programmatically Adding UITapGestureRecognizer To UIViews in Outlet Collection


I am working with a series of views stored in an outlet collection.

@IBOutlet var theViews: [UIView]!

In my viewDidLoad function I am looping over the collection of views during which I create a UITapGestureRecognizer and add it to the view.

for v in theViews {
    let tap = UITapGestureRecognizer(target: self, action: #selector(self.flipSingleView(sender:)))
    tap.delegate = self
    tap.numberOfTapsRequired = 1
    tap.numberOfTouchesRequired = 1
    v.addGestureRecognizer(tap)
    v.isUserInteractionEnabled = true
}

Here is the function that the selector points to:

@objc func flipSingleView(sender: UITapGestureRecognizer) {
    print("tapped")
}

Additional notes:

  • User interaction is enabled for these views
  • Breakpoint inside flipSingleView is never reached
  • The View Controller implements UIGestureRecognizerDelegate (I've looked through the protocol and don't see a function that would be useful in this situation)
  • Have Verified that all views in question have outlet connections to the outlet collection
  • Nothing prints to the console

Solution

  • You mentioned your views are in an outlet collection, so I'm assuming it looks something like this:

    @IBOutlet var myViews: [UIView]!
    

    Not sure you need everything you threw in there. Try this:

    // In viewDidLoad
    myViews.forEach{ view in
      let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(gesture:)))
      tap.numberOfTapsRequired = 1
      tap.delegate = self
      view.addGestureRecognizer(tap)
    }
    

    For your handler:

      @objc func handleTap(gesture: UIGestureRecognizer) {
        print("tap")
      }
    

    And lastly, put in a section for delegate methods, even if it's just empty:

    extension ViewController: UIGestureRecognizerDelegate {
      // TODO: Fill in as needed
    }
    

    To figure out which view sent it, you could add a tag to the view.