Dory Daniel
Dory Daniel

Reputation: 826

How can we add a UIGestureRecognizer to Outlet Collection?

I'm trying to add a tap gesture to an outlet collection of labels [UILabel], like this:

@IBOutlet var subLabels: [UILabel]!

    override func viewDidLoad() {
            super.viewDidLoad()

            let tap = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.selectSubLabel(tap:)))
            tap.numberOfTapsRequired = 1
            tap.cancelsTouchesInView = false

            for i in (0..<(subLabels.count)) {
                subLabels[i].addGestureRecognizer(tap)
            }
    }

    func selectSubLabel(tap: UITapGestureRecognizer) {
            print("Gesture Is WORKING!")
        }

and i tried to add it on a single label in storyboard; but NONE are working.

Upvotes: 0

Views: 1993

Answers (2)

Rafał Rębacz
Rafał Rębacz

Reputation: 495

Firstly, you need to allow user interaction on a label (it is turned off by default):

for i in (0..<(subLabels.count)) {
    subLabels[i].isUserInteractionEnabled = true
    subLabels[i].addGestureRecognizer(tap)
}

but gesture recognizer can observe for gestures only in one view. So, there are two options:

I. Dedicated gesture recognizer for every label

for i in (0..<(labels.count)) {
    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
    labels[i].isUserInteractionEnabled = true
    labels[i].addGestureRecognizer(tap)
}

II. One gesture recognizer for the parent view of the labels

override func viewDidLoad() {
    super.viewDidLoad()

    for i in (0..<(labels.count)) {
        subLabels[i].isUserInteractionEnabled = true
    }

    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
    view.addGestureRecognizer(tap)
}

func selectSubLabel(tap: UITapGestureRecognizer) {
    let touchPoint = tap.location(in: view)
    guard let label = subLabels.first(where: { $0.frame.contains(touchPoint) }) else { return }

    // Do your stuff with the label
}

Upvotes: 4

arunjos007
arunjos007

Reputation: 4355

Please check the User Interaction Enabled Attribute of your UIlabel's in Attribute inspector of Xcode. User Interaction Enabled must be ticked for detecting the tap. Please see the picture below,

enter image description here

Upvotes: 1

Related Questions