我如何更改 uialertcontroller 的文本字段内容?

How can i change uialertcontroller's textfield content?

我正在使用 UIAlertController 来获取这样的名称变量;

在android我的朋友可以在Alert Controller 弹出alert controller 时将变量放入Alert Controller 中;

他们可以将变量放在文本字段中并从中开始。

但是我做不到,我尝试了

alertController.textFields?.first?.text = myNameVariable

但是没用。

let alertController = UIAlertController(title: "Update Name", message: nil, preferredStyle: .alert)
            let confirmAction = UIAlertAction(title: "Update", style: .default) { (_) in
                if let txtField = alertController.textFields?.first, let text = txtField.text {
                    // operations
                    alertController.textFields?.first?.text = "Variable that i already have" // I want to change textfield content
                    print("Text==>" + text)
                }
            }
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
            alertController.addTextField { (textField) in
                textField.placeholder = "name"
            }
            alertController.addAction(confirmAction)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }))

抱歉上传了 IBB 而不是 Imgur,在我的国家 Imgur 被屏蔽了:/

您需要先添加文本字段才能访问它

这里有一个例子

let alertController = UIAlertController(title: "Update Name", message: nil, preferredStyle: .alert)

alertController.addTextField { textField in
    textField.text = "Text goes here 1"
    textField.placeholder = "placeholder"
    textField.tag = 0
}

alertController.addTextField { textField in
    textField.text = "Text goes here 2"
    textField.tag = 1
}

alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { _ in

    let firstTextField = alertController.textFields?.first
    let secondTextField = alertController.textFields?.last


    print(firstTextField?.text, secondTextField?.text)
}))

编辑

感谢@rmaddy

问题代码的问题是它试图在警报被解除后设置文本字段的文本。这没有什么意义。一旦用户点击其中一个警报按钮,用户就已经在文本字段中输入了文本。该代码应该尝试从文本字段中读取用户输入的文本,而不是尝试更新文本字段的文本。