Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextField Draggable in Swift iOS

Tags:

ios

swift

I want to drag textField around my view. but im having small problem with my code.

here my code

   override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        var touch : UITouch! = touches.first as! UITouch

        location = touch.locationInView(self.view)

        bottomTextField.center = location
    }

    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

        var touch : UITouch! = touches.first as! UITouch

        location = touch.locationInView(self.view)

        bottomTextField.center = location
    }

Problem is if i tried to touch on the TextField and drag then it doesn't work. but if i just touch somewhere else and drag my finger then TextField start to drag. i want t make it only if i touch on that textFiel.

like image 607
Im Batman Avatar asked Oct 29 '25 23:10

Im Batman


1 Answers

You can achieve this by adding a gesture to the text field:

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

}
like image 129
Kyle H Avatar answered Oct 31 '25 16:10

Kyle H