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

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(attachImage))
    let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
    tapGesture.numberOfTapsRequired = 1
    cell.image.addGestureRecognizer(tapGesture)
    cell.image.addGestureRecognizer(longGesture)

@objc func longPress(_ btn : UIButton) {
        selectedImageIndex = btn.tag
    }
@objc func attachImage(_ btn : UIButton) {
        selectedImageIndex = btn.tag
    }

我按下按钮时出现以下错误
发送到实例0x2802ec000的选择器无法识别

最佳答案

更改功能如下

@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(_:)))

关于ios - 无法将UITapGestureRecognizer和UILongPressGestureRecognizer添加到UIButton,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55843459/

10-14 09:01