UIPanGestureRecognizer 处理程序使我的应用程序崩溃 - swift

UIPanGestureRecognizer handler crashes my applications - swift

我有一个包含 UIImageView 的应用程序。我在父 UIImageView 的子视图中画了一个小圆圈。我希望用户能够触摸并拖动主 UIImageView 中的蓝色小圆圈。我已经为这个子视图设置了一个UIPanGestureRecognizer。我正在尝试测试 UIPanGestureRecognizer 的处理程序是否被触发,但是当我触摸并拖动主 UIImageView 时,我的应用程序崩溃并出现以下错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView firstDotHandlerWithSender:]: unrecognized selector sent to instance 0x103507d80'

Swift:

var firstDotView: UIView?
@IBOutlet weak var imgView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    firstDotView = UIView.init()
    firstDotView?.frame = imgView.bounds
    imgView.addSubview(firstDotView!)

    // DRAW A FILLED IN BLUE CIRCLE
    drawBlueCircle()

    imgView.isUserInteractionEnabled = true
    firstDotView?.isUserInteractionEnabled = true

    // ADD GESTURE RECOGNIZER
    let firstDotPanRecgnzr = UIPanGestureRecognizer.init(target: firstDotView!, action: #selector(firstDotHandler(sender:)))
    firstDotView?.addGestureRecognizer(firstDotPanRecgnzr)
}


@objc func firstDotHandler(sender: UIPanGestureRecognizer) -> Void {

    print("translation ...")

    let firstDot = sender.view
    let translation = sender.translation(in: view)

    if(sender.state == .began || sender.state == .changed){
        firstDot?.center = CGPoint.init(x: (firstDot?.center.x)! + translation.x, y: (firstDot?.center.y)! + translation.y)
        sender.setTranslation(CGPoint.zero, in: self.view)
    }
}

func drawBlueCircle(){
    let layer = CAShapeLayer()
    layer.path = UIBezierPath.init(roundedRect: CGRect.init(x: 60, y: 60, width: 30, height: 30), cornerRadius: 50).cgPath
    layer.fillColor = UIColor.blue.cgColor
    firstDotView?.layer.addSublayer(layer)
}

你的UIPanGestureRecognizer目标错误的

let firstDotPanRecgnzr = UIPanGestureRecognizer(target: self, action: #selector(firstDotHandler(sender:)))

target 告诉平移手势您的选择器所在的位置。我认为您混淆了它应该作用于哪个元素。 (我刚来的时候也犯过同样的错误:D)


来自docs.

target

An object that is the recipient of action messages sent by the receiver when it recognizes a gesture. nil is not a valid value.