Search code examples
iosswiftuialertcontrollerfirst-responder

iOS: textField on UIAlertController becoming first responder on alert present


I am adding textField to UIAlertController with the code below:

let anAlertController = UIAlertController(title:title, message:message, preferredStyle: .alert)
        weak var weakSelf = self

        let aDefaultAction = UIAlertAction(title:defaultTitle, style: UIAlertAction.Style.default) {
            UIAlertAction in

        anAlertController.addAction(aDefaultAction)
    }

    let aCancelAction = UIAlertAction(title:canceltTitle, style: UIAlertAction.Style.cancel) {
        UIAlertAction in
    }
    anAlertController.addAction(aCancelAction)

    anAlertController.addTextField { (textField) in
        textField.textAlignment = NSTextAlignment.center
        textField.text = "textFieldText"
        textField.delegate = self
        textField.resignFirstResponder()
    }
    self.present(anAlertController, animated: true, completion: nil)

When i try to present UIAlertController, textfield becoming first responder automatically. I don’t want textfield should become first responder while presenting alert. i Googled and tried several ways to avoid this but no luck. Can anybody tell how to achieve this?


Solution

  • try this

    anAlertController.addTextField { (textField) in
            textField.textAlignment = .center
            textField.text = "textFieldText"
            textField.delegate = self as? UITextFieldDelegate
            textField.isEnabled = false
    
        }
        self.present(anAlertController, animated: false, completion: {
            if let getTextfield  = anAlertController.textFields?.first{
                    getTextfield.resignFirstResponder()
                    getTextfield.isEnabled = true
            }
    
        })