UIAlertController's textfield delegate does not get called

不打扰是莪最后的温柔 提交于 2019-12-10 15:47:58

问题


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)

and in the same class, the delegate:

func textField(textField: UITextField!,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String!) -> Bool {

回答1:


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)


来源:https://stackoverflow.com/questions/24852868/uialertcontrollers-textfield-delegate-does-not-get-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!