UIButton的单按和长按事件很快

Kam*_*ena 13 iphone uibutton ios swift

我想在button click和上触发两个动作button long click.我UIbutton在我的界面构建器中添加了一个.如何触发两个动作使用IBAction有人可以告诉我如何归档这个?

这是我用于点击按钮的代码

@IBAction func buttonPressed (sender: UIButton) { .... }

我可以使用这种方法或我必须使用另一种方法进行长时间点击?

Dha*_*esh 38

如果您想通过单击您执行任何操作并长按,您可以通过以下方式将按钮添加到按钮:

@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")
}
Run Code Online (Sandbox Code Playgroud)

这样你可以为单个按钮添加多个方法,你只需要那个按钮的Outlet.


Mur*_*jed 13

@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)
}
Run Code Online (Sandbox Code Playgroud)