Search code examples
iosswift3uilabeluitapgesturerecognizeriboutletcollection

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.


Solution

  • 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