我在ImageView子类中定义了手势识别器,但是在ViewController中调用一个方法会因为“无法识别的选择器”而崩溃。如果我在VC中定义手势,这个手势就可以工作,但是我试图将代码放入custom view类中,以减少混乱。
这可能吗?这就是我要做的:

class DetailPhotoImageView: UIImageView {

func setupGestures(){

    let tapped = UITapGestureRecognizer(target: self, action: #selector(TripDetailVC.tapped(_:)))
    tapped.numberOfTapsRequired = 2

    addGestureRecognizer(tapped)

    }
}

然后在VC中我有了这个函数并调用imageView.setupGestures()
func tapped(_ gesture:UIGestureRecognizer) {
    if let tapGesture = gesture as? UITapGestureRecognizer {
        switch tapGesture.numberOfTapsRequired {
        case 2:
            print("Worked")
        default:
            break
        }
    }
}

最佳答案

所以放弃了Randall Wang的建议,他们是对的,你也可以用另一种节省空间的方式。将viewController作为参数传递,并将其设置为目标:

class DetailPhotoImageView: UIImageView, UIGestureRecognizerDelegate {

    func setupGestures(_ target: UIViewController) {
        guard let aTarget = target as? MyViewController else { return }

        let tap =  UITapGestureRecognizer(target: aTarget, action: #selector(aTarget.someAction(_:)))
        tap.delegate = self
        tap.numberOfTapsRequired = taps
        addGestureRecognizer(tap)
    }
}

在viewController类中:
detailPhoto.setupGestures(self)

10-06 02:56