我无法使用UITextFieldDelegate
. 委托已正确设置,但未在 UIAlertController 中为 UITextField 调用。
基于此处的答案How do I validate TextFields in an UIAlertController? 我了解到您可以在编辑更改时使用addTarget
forUIControl.Event.editingChanged
来调用选择器。
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)
您可以扩展或继承 UIAlertController 以添加选择器:
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
}
}