iOS:UIAlertController上的textField成为当前警报的第一响应者

时间:2019-02-06 09:18:30

标签: ios swift uialertcontroller first-responder

我正在使用以下代码将textField添加到UIAlertController:

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)

当我尝试呈现UIAlertController时,文本字段自动成为第一响应者。我不希望文本字段在发出警报时成为第一响应者。我用谷歌搜索并尝试了几种方法来避免这种情况,但是没有运气。谁能告诉我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

尝试

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
        }

    })

答案 1 :(得分:0)

您可以暂时禁用UITexField,它不会在出现警报时做出响应:

anAlertController.addTextField { (textField) in
    textField.textAlignment = NSTextAlignment.center
    textField.text = "textFieldText"
    textField.isEnabled = false
    DispatchQueue.main.async { textField.isEnabled = true }
}