Search code examples
uitextfieldswiftuitextfielddelegateuialertcontroller

UIAlertController's textfield delegate does not get called


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 {

Solution

  • 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)