swift: UIButton 長按 Long Press 範例

2019070820:08



Swift 4+

#1
@IBOutlet weak var btn: UIButton!

override func viewDidLoad() {

    let tapGesture = UITapGestureRecognizer(target: self, #selector (tap)) //短按
    let longGesture = UILongPressGestureRecognizer(target: self,  action: #selector(long)) //長按
    tapGesture.numberOfTapsRequired = 1
    btn.addGestureRecognizer(tapGesture)
    btn.addGestureRecognizer(longGesture)
}

@objc func tap() {
    print("Tap happend")
}

@objc func long() {
    print("Long press")
}



#2
@IBOutlet weak var countButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    addLongPressGesture()
}


func addLongPressGesture(){
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
    longPress.minimumPressDuration = 1.5 //觸發時間, default 0.5sec
    self.countButton.addGestureRecognizer(longPress)
}

@IBAction func countAction(_ sender: UIButton) {
    print("Single Tap")
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizerState.began {
        print("Long Press")
    }
}


UIButton with single press and long press events swift