Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change label color with UITapGestureRecognizer

I have a label with UITapGestureRecognizer and longgestureRecognizer:

let gestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("labelPressed:"))
let longgestureRecognizer = UILongPressGestureRecognizer(target: self, action: Selector("longLabelPressed:"))
label.addGestureRecognizer(gestureRecognizer)
label.addGestureRecognizer(longgestureRecognizer)

I want to change color like in UIButton, when it pressed:

func longLabelPressed(recognizer:UILongPressGestureRecognizer){
        if let label = recognizer.view as? UILabel {
            if recognizer.state == .Began {
                label.textColor = UIColor.redColor()
            }

            if recognizer.state == .Ended {
                label.textColor = UIColor.blackColor()
            }



        }
    }

But how to detect tap end event ?

func labelPressed(recognizer:UITapGestureRecognizer) {
        if let label = recognizer.view as? UILabel {

        }

    }

My goal is create label like UIButton with touch events.

like image 799
Arti Avatar asked Jan 07 '16 13:01

Arti


People also ask

How do you add a tap gesture to a label?

Create a new project and name it How To Add Gesture to UILabel. // Do any additional setup after loading the view. We just created a setupLabelTap() function where we've created a UITapGestureRecognizer which will fire a labelTapped() function. It is simple.

How do I make a label Tappable in Swift?

To make UILabel clickable you will need to enable user interaction for it. To enable user interaction for UILabel simply set the isUserInteractionEnabled property to true.

How to set tap gesture in ios?

You don't need to switch between the code editor and Interface Builder. Open Main. storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the view we added earlier. The tap gesture recognizer appears in the Document Outline on the left.


1 Answers

UserInteractionEnabled for label is by default false . so if you are using its label outlet then enable it from (XIB/ storyboard)

Now to make label same like button using UILongPressGestureRecognizer and then you event called successfully but you write label color change code in UILongPressGestureRecognizer so its take some time(default time) to detect touch event. recognizer.state == .Began so change minimum time for long pressGesture

longgestureRecognizer.minimumPressDuration = 0.001

using that recognizer.state == .Began will call quickly .

like image 63
Jaydeep Patel Avatar answered Sep 21 '22 06:09

Jaydeep Patel