Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UITextField to String in Swift

Tags:

swift

I'm trying to convert a UITextField object to a String so that I can pass it to a function in my model file. But it is printing a blank even after I type in some characters in the name input text field and then click outside of it. Why is nothing stored there?

In view controller file:

@IBOutlet weak var nameInputText: UITextField!

  override func viewDidLoad() {


    super.viewDidLoad()
    nameInputText.delegate = self
    let text: String = nameInputText.text!
    print(text) //this prints a blank
    model.validateName(nametext: text)

}
like image 609
Kevin Avatar asked Oct 17 '22 10:10

Kevin


1 Answers

It should be like below

    @IBOutlet weak var usernameInputText : UITextField!

      override func viewDidLoad() {

        super.viewDidLoad()
        usernameInputText.delegate = self
    }

    func ClickOnButton()
    {
      let text: String = usernameInputText.text!
        print(text) //this prints My text
        model.validateName(nametext: text)
    }

func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String)
        -> Bool
    {
       let text: String = usernameInputText.text!
        print(text) //this prints My text
        model.validateName(nametext: text)
    }
like image 134
Vibha Singh Avatar answered Oct 21 '22 04:10

Vibha Singh