I want to trigger two action on button click
and button long click
. I have add a UIbutton
in my interface builder. How can i trigger two action using IBAction
can somebody tell me how to archive this ?
this is the code i have used for a button click
@IBAction func buttonPressed (sender: UIButton) {
....
}
can i use this method or do i have to use another method for long click ?
Just drag a Long Press Gesture Recognizer from the Object Library and drop it on top of the button where you want the long press action. The difference is that with Ended , you see the effect of the long press when you lift your finger.
A control that executes your custom code in response to user interactions.
If you want to perform any action with single tap you and long press the you can add gestures into button this way:
@IBOutlet weak var btn: UIButton!
override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, #selector (tap)) //Tap function will call when user tap on button
let longGesture = UILongPressGestureRecognizer(target: self, #selector(long)) //Long function will call when user long press on button.
tapGesture.numberOfTapsRequired = 1
btn.addGestureRecognizer(tapGesture)
btn.addGestureRecognizer(longGesture)
}
@objc func tap() {
print("Tap happend")
}
@objc func long() {
print("Long press")
}
This way you can add multiple method for single button and you just need Outlet for that button for that..
@IBOutlet weak var countButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
addLongPressGesture()
}
@IBAction func countAction(_ sender: UIButton) {
print("Single Tap")
}
@objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.began {
print("Long Press")
}
}
func addLongPressGesture(){
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
longPress.minimumPressDuration = 1.5
self.countButton.addGestureRecognizer(longPress)
}
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