UIButton带有单击和长按事件的Swift

22

我想在按钮点击和长按时触发两个动作。我已经在我的界面构建器中添加了一个UIbutton。请问如何使用IBAction来触发两个动作?有人可以告诉我如何实现吗?

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

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

我可以使用这种方法吗,还是必须使用另一种方法来实现长按?


1
请查看此链接:https://dev59.com/M1nUa4cB1Zd3GeqPXiTc - Yatheesha
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即可实现。


我在我的用户界面中有多个按钮,因为它们都执行相同的操作,所以我将它们映射到此方法(@IBAction func buttonPressed(sender: UIButton))中。我能否通过编程方式添加方法? - Kamal Upasena
哦,我的UI界面有30个按钮,就像一个键盘:( 有没有不使用outlet的方法来实现它们? - Kamal Upasena
我们能否通过编程方式映射IBAction?这样我只需要为一个按钮创建出口即可。 - Kamal Upasena
当我尝试添加手势时,出现了这样的错误:“致命错误:在解包可选值时意外地发现了nil”。有什么想法吗? - Kamal Upasena
让我们在聊天中继续这个讨论 - Dharmesh Kheni
显示剩余6条评论

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
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接