Reputation: 107
I want my button to change its background image when the user clicks on it twice. For this purpose i am using touchDownRepeat event. However it does not works.
button.addTarget(self, action: #selector(clickedRepeatOnPlate), for: .touchDownRepeat)
Upvotes: 2
Views: 867
Reputation: 5212
As for the Apple's oficial documentation about .touchDownRepeat
:
A repeated touch-down event in the control; for this event the value of the UITouch tapCount method is greater than one.
This event will trigger every time the user taps the button more than once, so four taps will trigger the event three times.
To trigger only double taps, you need to create a UITapGesture
and set 2 on its numberOfTapsRequired
:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickedRepeatOnPlate))
tapGesture.numberOfTapsRequired = 2
button.addGestureRecognizer(tapGesture)
Edit
If you need to get the sender button as a function parameter, you can do as follows:
func addDoubleTapEvent() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickedRepeatOnPlate(gesture:)))
tapGesture.numberOfTapsRequired = 2
button.addGestureRecognizer(tapGesture)
}
@objc func clickedRepeatOnPlate(gesture: UITapGestureRecognizer) {
guard let button = gesture.view as? UIButton else { return }
print(button.titleLabel?.text)
}
Output
Optional("button")
Upvotes: 4
Reputation: 836
This let you to set a gesture for double tap on a view.
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
view.addGestureRecognizer(tap)
Remember that a UIButton is a UIView
Upvotes: 1