Search code examples
iostextfielduipangesturerecognizerprogrammatically-created

Moving programmatically created UItTextFields


I am trying to utilise panGestureRecogniser to enable users of my first app to move programmatically created textfields. Having searched for the solution I only found outdated code, for IBOutlets. The problem is that I struggle with setting the position of newly created textfields to the position that the users drags to. Everything is working just fine, when I test my code on a textfield create in a storyboard, connected via an IBOutlet. My problem is how to make a connection between the location from the didPan function and any new label created by generateTextField func. Another thing is that I want mu users to be able to create many textfields and each should be draggable, so any solution should include that. I paste my code below:

override func viewDidLoad() {
    super.viewDidLoad()

}

func generateTextField() {

    let textPanel = UITextField(frame: CGRect(x: 50, y: 50, width: 100, height: 30))
    textPanel.textAlignment = NSTextAlignment.center
    textPanel.textColor = UIColor.blue
    textPanel.borderStyle = UITextBorderStyle.line
    self.view.addSubview(textPanel)

    let gest = UIPanGestureRecognizer(target: self, action: #selector(didPan))

    textPanel.isUserInteractionEnabled = true
    textPanel.addGestureRecognizer(gest)

}

@objc func didPan(sender: UIPanGestureRecognizer){

    let location = sender.location(in: view)

    if sender.state == .began {
        print("Gesture began")
    } else if sender.state == .changed {
        print("Gesture is changing")
    } else if sender.state == .ended {
        print("Gesture ended")
    }
}


@IBAction func generateTextFieldPressed(_ sender: Any) {
    generateTextField()
}

Solution

  • In didPan you can retrieve textField from recognizer like:

    let textField = sender.view as TextField
    

    And after that change textField's frame.