I was unable to get this working with UITextFieldDelegate. The delegate was set correctly but not being called for the UITextField within a UIAlertController.
Based on the answer here How do I validate TextFields in an UIAlertController? I learned you can instead use addTarget for UIControl.Event.editingChanged to call a selector when the editing changes.
let alertController = UIAlertController(title: "Title", message: "message", preferredStyle: .alert) alertController.addTextField { (textField : UITextField!) -> Void in /* * Alternative to UITextFieldDelegate */ textField.addTarget(alertController, action: #selector(alertController.textDidChange), for: .editingChanged) } let searchAction = UIAlertAction(title: "Search", style: .default) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil ) alertController.addAction(searchAction) alertController.addAction(cancelAction) present(searchAlertController, animated: true)
You can extend or subclass UIAlertController to add the selector:
extension UIAlertController { @objc func textDidChange() { guard let textField = textFields?.first else { return } guard let searchAction = actions.first(where: { $0.title == "Search" }) else { return } let text = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" searchAction.isEnabled = !text.isEmpty } }