具有单按和长按事件的 UIButton swift

问题描述 投票:0回答:3

我想在

button click
button long click
上触发两个动作。我在我的界面生成器中添加了一个
UIbutton
。我如何使用
IBAction
触发两个动作有人可以告诉我如何存档吗?

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

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

我可以使用这种方法还是必须使用其他方法才能长按?

ios iphone swift uibutton
3个回答
57
投票

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

@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")
}

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


15
投票
@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)
}

-1
投票

为什么不创建一个自定义的 UIButton 类,创建一个协议并让按钮发送回委托信息。像这样的东西:

    //create your button using a factory (it'll be easier of course)
    //For example you could have a variable in the custom class to have a unique identifier, or just use the tag property)

    func createButtonWithInfo(buttonInfo: [String: Any]) -> CustomUIButton {
        let button = UIButton(type: .custom)
        button.tapDelegate = self
        /*
Add gesture recognizers to the button as well as any other info in the buttonInfo

*/
        return button
    }

    func buttonDelegateReceivedTapGestureRecognizerFrom(button: CustomUIButton){
        //Whatever you want to do
    }
© www.soinside.com 2019 - 2024. All rights reserved.