无法将UITapGestureRecognizer和UILongPressGestureRecognizer添加到UIButton

时间:2019-04-25 06:54:31

标签: ios swift iphone uibutton

我正在使用以下代码段添加手势识别器:

        SpUsers.setUser("user_name you want to allow login");

按下按钮时出现以下错误

  

无法识别的选择器已发送到实例0x2802ec000

2 个答案:

答案 0 :(得分:2)

如下更改功能

@objc func longPress(_ sender : UILongPressGestureRecognizer) {
    if let btn = sender.view {
        selectedImageIndex = btn.tag
    }
}
@objc func attachImage(_ sender : UITapGestureRecognizer) {
    if let btn = sender.view {
        selectedImageIndex = btn.tag
    }
}

并如下更改手势初始化

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(attachImage(_:)))
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))

答案 1 :(得分:0)

如果您在imageView上添加手势,则必须启用isUserInteractionEnabled

imageView.isUserInteractionEnabled = true

如果您在UIButton上添加手势,则

@IBOutlet weak var button: UIButton!

override func viewDidLoad() {

    let tapGesture = UITapGestureRecognizer(target: self, #selector (tapGestureActionHandler(_:)))  //Tap function will call when user tap on button
    let longGesture = UILongPressGestureRecognizer(target: self, #selector(longGestureActionHandler(_:)))  //Long function will call when user long press on button.
    tapGesture.numberOfTapsRequired = 1
    button.addGestureRecognizer(tapGesture)
    button.addGestureRecognizer(longGesture)
}

@objc func tapGestureActionHandler(_ gesture: UITapGestureRecognizer) {

    print("Tap happend")
}

@objc func longGestureActionHandler(_ gesture: UILongPressGestureRecognizer) {

    print("Long press")
}