How to add text to an active UITextField

2020-04-21 05:09发布

问题:

I have a couple of UITextField's and one UIButton. If I tap on the UIButton, I want to place some static text in the active UITextField.

So something like:

@IBAction func buttonEen(sender: UIButton) {
    'active textField'.text = "static text"
}

But how do I determine which UITextField is the active UITextField and how do I reach it?

回答1:

To write text in last active UITextField you have to make your UIViewController a delegate of UITextField

ex:

class ViewController: UIViewController, UITextFieldDelegate

declare a activeField variable

ex:

var activeField: UITextField?

then implements textFieldDidBeginEditing

ex:

func textFieldDidBeginEditing(textField: UITextField)
{
    activeField = textField
}

So your button function will be something like

@IBAction func buttonEen(sender: UIButton) {
if activeField
    {
        activeField.text = "static text"
    }

}


回答2:

First you need to create your textfield delegate (probably in 'ViewDidLoad()') :

activeTxtField.delegate = self

Then you need to implement the textField delegate function:

extension 'YourVC': UITextFieldDelegate {

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == activeTxtField {
        // Do whatever you want
        // e.g set textField text to "static text"
     }
  }
}