【问题标题】:iOS: textField on UIAlertController becoming first responder on alert presentiOS:UIAlertController 上的 textField 成为当前警报时的第一响应者
【发布时间】:2019-02-06 09:18:30
【问题描述】:

我正在使用以下代码将 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 时,文本字段会自动成为第一响应者。我不希望 textfield 在呈现警报时成为第一响应者。我用谷歌搜索并尝试了几种方法来避免这种情况,但没有运气。谁能告诉我如何做到这一点?

【问题讨论】:

  • 显示一些与此相关的附加代码
  • @Anbu.Karthik 更新了代码。请检查
  • 你检查我的答案吗? stackoverflow.com/a/54550421/820795
  • @Gralex。仍然弹出键盘
  • 你确定你没有遗漏什么吗?检查模拟器和设备(iOS 12),一切正常。

标签: ios swift uialertcontroller first-responder


【解决方案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
        }

    })

【讨论】:

  • 警报出现时您会看到键盘
  • @Anbu.karhtik。我试过这个,但它显示键盘一段时间然后出现。它不会工作
  • @Gralex - 是的,请给我尝试解决这个问题的时间
  • @lazyCoder - 检查更新的答案 Gralex - 感谢您的参考
  • @lazyCoder - 检查此参考:stackoverflow.com/questions/1920541/…
【解决方案2】:

你可以暂时禁用UITexField,它不会是响应者出现的警报:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2018-02-17
    • 1970-01-01
    相关资源
    最近更新 更多