平移手势不适用于控制器中的按钮



我正在开发一个使用UIGestureRecognizers的应用程序UI。我正在使用平移手势来移动控制器中的按钮。它没有移动。如果我调试它,那么我可以看到这个draggedButton方法正在执行,但气泡按钮没有移动。

我使用的代码是

private var panGesture = UIPanGestureRecognizer()
panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedButton(sender:)))
bubbleButton.isUserInteractionEnabled = true
bubbleButton.addGestureRecognizer(panGesture)

@objc func draggedButton(sender:UIPanGestureRecognizer) {
self.view.bringSubview(toFront: bubbleButton)
let translation = sender.translation(in: self.view)
let xPostion = bubbleButton.center.x + translation.x
let yPostion = bubbleButton.center.y + translation.y - bubbleButton.frame.height
if (xPostion >= 0 && xPostion <= self.view.frame.size.width) &&  (yPostion >= 0 && yPostion <= self.view.frame.size.height)  {
bubbleButton.center = CGPoint(x: bubbleButton.center.x + translation.x, y: bubbleButton.center.y + translation.y)
sender.setTranslation(.zero, in: self.view)
}
}

尝试添加:

panGesture.cancelsTouchesInView = true

最新更新