iosswiftuipangesturerecognizer

Swift iOS: Detect when a user drags/slides finger over a UILabel?


I have a project where I’m adding three UILabels to the view controller’s view. When the user begins moving their finger around the screen, I want to be able to determine when they their finger is moving over any of these UILabels.

I’m assuming a UIPanGestureRecognizer is what I need (for when the user is moving their finger around the screen) but I’m not sure where to add the gesture. (I can add a tap gesture to a UILabel, but this isn’t what I need)

Assuming I add the UIPanGestureRecognizer to the main view, how would I go about accomplishing this?

if gesture.state == .changed { 
    // if finger moving over UILabelA… 
    // …do this 
    // else if finger moving over UILabelB… 
    // …do something else 
}

Solution

  • You can do this with either a UIPanGestureRecognizer or by implementing touchesMoved(...) - which to use depends on what else you might be doing.

    For pan gesture, add the recognizer to the view (NOT to the labels):

    @objc func handlePan(_ g: UIPanGestureRecognizer) {
        
        if g.state == .changed {
            // get the location of the gesture
            let loc = g.location(in: view)
            // loop through each label to see if its frame contains the gesture point
            theLabels.forEach { v in
                if v.frame.contains(loc) {
                    print("Pan Gesture - we're panning over label:", v.text)
                }
            }
        }
        
    }
    

    For using touches, no need to add a gesture recognizer:

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let t = touches.first {
            // get the location of the touch
            let loc = t.location(in: view)
            // loop through each label to see if its frame contains the touch point
            theLabels.forEach { v in
                if v.frame.contains(loc) {
                    print("Touch - we're dragging the touch over label:", v.text)
                }
            }
        }
    }