Vladislav
Vladislav

Reputation: 273

How to move textfield?

I have textfield.

let textFld = UITextField(frame: CGRect(x: 250, y: 
100, width: 200, height: 40))
textFld.placeholder = "Enter text here"
textFld.font = UIFont.systemFont(ofSize: 15)
textFld.borderStyle = UITextBorderStyle.roundedRect
textFld.autocorrectionType = UITextAutocorrectionType.no
textFld.keyboardType = UIKeyboardType.default
textFld.returnKeyType = UIReturnKeyType.done
textFld.clearButtonMode = UITextFieldViewMode.whileEditing;
textFld.contentVerticalAlignment = UIControlContentVerticalAlignment.center

self.view.addSubview(textFld)

I want to move textfield with finger on screen. What do I need to do? Error

Bug

Upvotes: 0

Views: 639

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

Using a pan gesture recognizer you can do the trick here in this answer of my own I explain it a little further Drag UIButton without it shifting to center [Swift 3]

this code should work for you

import UIKit

class DraggableUITextFieldViewController: UIViewController {

        @IBOutlet weak var textField: UITextField!

        var textFieldOrigin : 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(textFieldDrag(pan:)))
            self.textField.addGestureRecognizer(gesture)

            self.textField.layer.borderWidth = 1
            self.textField.layer.borderColor = UIColor.red.cgColor
        }

        @objc func textFieldDrag(pan: UIPanGestureRecognizer) {
            print("Being Dragged")
            if pan.state == .began {
                print("panIF")
                textFieldOrigin = pan.location(in: textField)
            }else {
                print("panELSE")
                let location = pan.location(in: view) // get pan location
                textField.frame.origin = CGPoint(x: location.x - textFieldOrigin.x, y: location.y - textFieldOrigin.y)
            }
        }
}

Result

enter image description here

Upvotes: 3

Related Questions