Reputation: 876
I have a UIAlertController
with a UITextField
and a submit button. The code looks like this:
let saveDialogue = UIAlertController(title: "Save Level",
message: "",
preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default,
handler: { (action) in
let textfield = saveDialogue.textFields![0] as UITextField
// do something with the textfield
}
)
saveAction.enabled = false
saveDialogue.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "My Level"
textField.text = filename
// conditionally enable the button
textField.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
}
While the button cannot be tapped, hitting the return key on the keyboard triggers the default action (saveAction
).
Is there a way around this? I also tried to validate the textfield value in the handler, but the view will be dismissed. Can it be retained?
Upvotes: 1
Views: 1274
Reputation: 2857
I did solve the same problem little bit differently.
//where alert is variable in class
override func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if range.location >= 1 { return true } // if we have one or more characters
guard let isTextFieldEmpty = textField.text?.isEmpty else { return true }
if !isTextFieldEmpty {
alert?.actions.first?.isEnabled = false
} else {
alert?.actions.first?.isEnabled = true
}
return true
}
Upvotes: 0
Reputation: 10573
If you want to ignore the return key input, set textField's delegate and return false in textFieldShouldReturn:
delegate method.
Like bellow:
saveDialogue.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "My Level"
textField.text = "hello"
// conditionally enable the button
textField.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
// Add this line
textField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return false
}
Upvotes: 5