拖动UIButton,而不移动到中心

所以我find了如何使用UIPanGestureRecognizer使button可拖动。 但我知道如何做的唯一方法是通过存储和拖动button的中心。 这个问题是,如果你尝试从一个angular落拖动button,button会立即从angular落移动到中心。 我正在寻找的是一个解决scheme,将保持我的手指在选定的地方,而没有立即locking中心移动。

我目前使用的代码是:

func buttonDrag(pan: UIPanGestureRecognizer) { print("Being Dragged") if pan.state == .began { print("panIF") buttonCenter = button.center // store old button center }else { print("panELSE") let location = pan.location(in: view) // get pan location button.center = location // set button to where finger is } } 

提前致谢。

这可以至less以两种不同的方式完成,一种是使用GestureRecognizer 你的问题的方式和其他方式是UIView子类化和实现touchesBegantouchesMovedtouchesEndedtouchesCancelled一般将工作任何UIView子类可以是UIButtonUILabelUIImageView等…

在你的方式,使用GestureRecognizer我做了一些改变,你仍然需要一个var来保持在你的UIButton的触摸的原点CGPoint ,所以我们得到相对于UIButton的触摸位置,当拖动继续根据原点调整UIButton的原点触摸位置和运动的位置

方法1手势识别器

 import UIKit class ViewController: UIViewController { @IBOutlet weak var button: UIButton! var buttonOrigin : CGPoint = CGPoint(x: 0, y: 0) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let gesture = UIPanGestureRecognizer(target: self, action: #selector(buttonDrag(pan:))) self.button.addGestureRecognizer(gesture) } func buttonDrag(pan: UIPanGestureRecognizer) { print("Being Dragged") if pan.state == .began { print("panIF") buttonOrigin = pan.location(in: button) }else { print("panELSE") let location = pan.location(in: view) // get pan location button.frame.origin = CGPoint(x: location.x - buttonOrigin.x, y: location.y - buttonOrigin.y) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

方法2在这种情况下UIView子类UIButton子类

使用这个UIButton子类

 import UIKit class DraggableButton: UIButton { var localTouchPosition : CGPoint? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) let touch = touches.first self.localTouchPosition = touch?.preciseLocation(in: self) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) let touch = touches.first guard let location = touch?.location(in: self.superview), let localTouchPosition = self.localTouchPosition else{ return } self.frame.origin = CGPoint(x: location.x - localTouchPosition.x, y: location.y - localTouchPosition.y) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) self.localTouchPosition = nil } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) self.localTouchPosition = nil } } 

结果

在这里输入图像说明

在这里输入图像说明

希望这可以帮助你