1

My code doesn't work, can you point out whats wrong. I am trying to validate user input in SNameInput, error label should change it's text when the input is not valid and STitle should change it's text when user is done typing in SNameInput and it is valid, thanks!

func textFieldDidChange(SNameInput: UITextField) {
        let d = ""
        if (SNameInput.isEqual(d)||(SNameInput.text?.characters.count)! >= 21) {
            errorLabel.text = "Name has to be a t least 1 character and not longer than 20"}
        else{  errorLabel.text = ""
            Stitle.text = SNameInput.text}
    }
3
  • Did you set textfield delegate to self? Commented Aug 6, 2017 at 3:01
  • is your delegate method called?? Commented Aug 6, 2017 at 3:02
  • You have strange expressions like (SNameInput: UITextField) SNameInput.isEqual(d). Also, your English sentences are very difficult to understand since you don't end each sentence with the period. Commented Aug 6, 2017 at 3:11

1 Answer 1

2

Possibility: you didn't add editingDidEnd action to your SNameInput text field.

editingDidEnd: A touch ending an editing session in a UITextField object by leaving its bounds.

override func viewDidLoad() {
    super.viewDidLoad()

    SNameInput.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingDidEnd)
}

@IBAction func textFieldDidChange(_ sender: UITextField) {
    guard let string = sender.text else { return }

    if (string.isEmpty || string.characters.count >= 21) {
        errorLabel.text = "Name has to be a t least 1 character and not longer than 20"
    }
    else{
        errorLabel.text = ""
        Stitle.text = string
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.