I have an alertController, with one textField.. and alertAction button [Save].
When the textField presented (empty), the [Save].isEnabled = false. If user type anything in textField (none space), button [Save].isEnabled = true.
code:
field.addTarget(self, action: #selector(self.alertTextFieldDidChange(_:)), for: .editingChanged)
validation code:
var alertController : UIAlertController?
@objc func alertTextFieldDidChange(_ sender: UITextField) {
alertController?.actions[0].isEnabled = sender.text!.trimmingCharacters(in: .whitespacesAndNewlines).count > 0
}
[Save] button works as expected. However, when I insert text in textField (as default entry):
textField.text = "Test"
textField showing "Text", if user choose to accept the default value "Test", [Save] button isEnabled will not change. User will have to type something in textField.
I need some direction .. Thanks.
Why do you enter a default text and not a placeholder ?
Placeholder isn’t the right choice for proposing text that the user may choose to accept without further editing; it should be used as a hint to help the user know what to enter. For example, if saving a new document the default (proposed) name could be Untitled and the placeholder could be Enter a name. The placeholder would appear only if the user erases the proposed name.
And here’s a tip on enabling the button to match the text. If you reuse the text change handler for .editingDidBegin
like this:
textField.addTarget(self, action: #selector(self.alertTextFieldDidChange), for: .editingDidBegin)
textField.addTarget(self, action: #selector(self.alertTextFieldDidChange), for: .editingChanged)
...then it will get called just before the alert appears, but after the needed alert?.actions
array is set up. So now your enable/disable logic can be in just one place.