我已将UITextField添加到UIAlertController,但不会触发shouldChangeCharactersInRange
。为什么?我设置了代表。
let alertController = UIAlertController(title: "", message: "xxx", preferredStyle: .Alert)
self.presentViewController(alertController, animated:true, completion:nil)
let textField = UITextField()
textField.delegate = self
alertController.addTextFieldWithConfigurationHandler(nil)
并且在同一个类中,代表:
func textField(textField: UITextField!,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String!) -> Bool {
您要为其设置委托的文本字段与添加到警报控制器的文本字段不同。基本上,您正在创建UITextField的新实例,但从不为其提供框架,也不会将其添加到视图层次结构中。同时,您正在使用addTextFieldWithConfigurationHandler()
将文本字段添加到警报控制器,但从未设置该文本字段的委托。我相信这就是您想要的:
let alertController = UIAlertController(title: "", message: "xxx", preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler {[weak self] (textField: UITextField!) in
textField.delegate = self
}
self.presentViewController(alertController, animated:true, completion:nil)
我无法在UITextFieldDelegate
上使用它。正确设置了委托,但未在UIAlertController中为UITextField调用该委托。
基于此处的答案How do I validate TextFields in an UIAlertController?,我了解到您可以在编辑更改时使用addTarget
代替UIControl.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
}
}