T Race T Race - 5 months ago 13
Swift Question

How to detect if a textfield is empty in swift?

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

Answer

Fixing the other answer:

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

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