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.
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.
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.
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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With