UITapGestureRecognizer 静态方法崩溃

UITapGestureRecognizer static method crashes

我有一个包含多个自定义 UICollectionViewCell 的 swift 应用程序。所有的单元格都有多个用户可以点击的对象(UIImageViewUILabel)(因此,我使用多个 UITapGestureRecognizer 来调用相应的操作。现在,为了减轻我工作并减少代码重复,我想创建一个 UITapGestureRecognizerextension 和一个 static 方法,我可以直接在 class 上调用。

我做到了,但应用程序崩溃的事实意味着我有一些地方没有做好。这是我的代码:

extension UITapGestureRecognizer {
    static func addNewTapGuestureRecognizer(for imageView: UIImageView, selectorName: Selector) {
        let tap = UITapGestureRecognizer(target: self, action: selectorName)
        imageView.addGestureRecognizer(tap)
        imageView.isUserInteractionEnabled = true
    }

    static func addNewTapGuestureRecognizer(for label: UILabel, selectorName: Selector) {
        let tap = UITapGestureRecognizer(target: self, action: selectorName)
        label.addGestureRecognizer(tap)
        label.isUserInteractionEnabled = true
    }
}

class TextCVC: UICollectionViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        addTapGuesturesForImagesAndLabels()
    }

    func addTapGuesturesForImagesAndLabels() {
        UITapGestureRecognizer.addNewTapGuestureRecognizer(for: postActionShareImageVIew, selectorName: #selector(self.shareImageTapped))
        UITapGestureRecognizer.addNewTapGuestureRecognizer(for: postActionLikeImageVIew, selectorName: #selector(self.likeImageTapped))
    }

    @objc func shareImageTapped() {
        print("share")
    }

    @objc func likeImageTapped() {
    }
}

控制台错误显示:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[UITapGestureRecognizer likeImageTapped]: unrecognized selector sent to class 0x1b52e4c50'

问题似乎出在这里: let tap = UITapGestureRecognizer(target: self, action: selectorName)

目标不是 self,它是 UICollectionViewCell 的实例。

将您的代码更改为:

static func addNewTapGuestureRecognizer(for imageView: UIImageView, target: Any, selectorName: Selector) {
    let tap = UITapGestureRecognizer(target: target, action: selectorName)
    imageView.addGestureRecognizer(tap)
    imageView.isUserInteractionEnabled = true
}

问题出在目标中,所以替换这个

 static func addNewTapGuestureRecognizer(for imageView: UIImageView, selectorName: Selector) {

static func addNewTapGuestureRecognizer(for imageView: UIImageView, selectorName: Selector , myTarget:UICollectionViewCell) {

     let tap = UITapGestureRecognizer(target: myTarget, action: selectorName)


 }