UIAlertController 的文本字段委托不会被调用 [英] UIAlertController's textfield delegate does not get called
问题描述
我已经向 UIAlertController 添加了一个 UITextField,但是 shouldChangeCharactersInRange
不会被触发.为什么?我设置了委托.
I have added a UITextField to UIAlertController, but shouldChangeCharactersInRange
will get not fired. Why? I set the delegate.
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()
将文本字段添加到警报控制器,但您从未为此文本字段设置委托.我相信这就是你想要的:
The text field that you're setting the delegate for is not the same text field that is added to the alert controller. Basically, you're creating a new instance of UITextField, but never giving it a frame, or adding it to the view hierarchy. At the same time, you're using addTextFieldWithConfigurationHandler()
to add a text field to the alert controller, but you never set the delegate for this text field. I believe this is what you want:
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)
这篇关于UIAlertController 的文本字段委托不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!