1

Hello despite the question name, this question requests a bit more insight.

I want to know how to check if a textfield is empty but it must be able to detect this if contained text previously.

Here is my current code

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if textField == txtSitReach {

        if txtSitReach.text != nil {

            doneSitReachButton.enabled = true
        }
        else {
            doneSitReachButton.enabled = false
        }
    }
    else {
        print("whatever")
    }
2
  • 1
    if txtSitReach.text.isEmpty == true Commented Jun 23, 2016 at 22:44
  • no that solution invoked some very odd behavior. Essentially that did not work. Commented Jun 23, 2016 at 22:52

2 Answers 2

4

You could add a target checking the textfield when some changes has been made (i.e. adding some characters).

txtSitReach.addTarget(self, action: #selector(textDidChange), forControlEvents: .EditingChanged)

func textDidChange(textField: UITextField) {
    doneSitReachButton.enabled = txtSitReach.text?.isEmpty ?? false
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is so close! It does the opposite of what I want though. When the textfield is empty it is enabled and when it has text it is disabled
You can add a ! in front of txtSitReach.text?.isEmpty to do the opposite though. It wasn't very clear what you exactly wanted in your question :).
2

Fixing the other answer:

txtSitReach.addTarget(self, action: #selector(textDidChange), forControlEvents: .EditingChanged)

func textDidChange(textField: UITextField) {
    doneSitReachButton.enabled = !txtSitReach.text!.isEmpty
}

1 Comment

Nothing big, but you could have just edited my question and added the !. Now there are two "exact" the same answers, which could confuse other people. Just a tip for next time ;).

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.