How to add text to an active UITextField

久未见 提交于 2019-12-04 05:01:25

问题


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"
     }
  }
}


来源:https://stackoverflow.com/questions/30400367/how-to-add-text-to-an-active-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!