Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton with single press and long press events swift

Tags:

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 ?

like image 821
Kamal Upasena Avatar asked Jun 16 '15 05:06

Kamal Upasena


People also ask

How to add long press gesture Recognizer on UIButton?

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.

What is UIButton?

A control that executes your custom code in response to user interactions.


2 Answers

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..

like image 147
Dharmesh Kheni Avatar answered Sep 25 '22 13:09

Dharmesh Kheni


@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)
}
like image 30
Murad Al Wajed Avatar answered Sep 25 '22 13:09

Murad Al Wajed