TextField可在Swift iOS中拖拽

我想在我的视图中拖动textField。 但我的代码问题很小。

这是我的代码

override func touchesBegan(touches: Set, withEvent event: UIEvent) { var touch : UITouch! = touches.first as! UITouch location = touch.locationInView(self.view) bottomTextField.center = location } override func touchesMoved(touches: Set, withEvent event: UIEvent) { var touch : UITouch! = touches.first as! UITouch location = touch.locationInView(self.view) bottomTextField.center = location } 

问题是,如果我试图触摸TextField并拖动它然后它不起作用。 但是,如果我只是触摸其他地方并拖动我的手指然后TextField开始拖动。 我想要只有触摸那个textFiel才能成功。

您可以通过向文本字段添加手势来实现此目的:

 override func viewDidLoad() { super.viewDidLoad() var gesture = UIPanGestureRecognizer(target: self, action: Selector("userDragged:")) bottomTextField.addGestureRecognizer(gesture) bottomTextField.userInteractionEnabled = true } func userDragged(gesture: UIPanGestureRecognizer){ var loc = gesture.locationInView(self.view) self.bottomTextField.center = loc }