Chris C.
Chris C.

Reputation: 80

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:

Upvotes: 2

Views: 545

Answers (1)

Adrian
Adrian

Reputation: 16725

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.

Upvotes: 2

Related Questions