在 Swift 中,警报关闭中的命令在 UI 警报执行之前执行?

In Swift, Commands in alert closure executed before UI alert be executed?

基于以下代码,alert函数中闭包中的命令在执行用户界面之前执行。它导致,闭包中的变量为空?

func callAlert2() {
    let alert = UIAlertController(title: "Add Contact", message: "Please fill the form", preferredStyle: .alert)


    alert.addTextField { textField in
        textField.placeholder = "Name"
        self.contact.name = textField.text
    }

    alert.addTextField { (textField) in
        textField.placeholder = "Surname"
        self.contact.surname = textField.text
    }

    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (action) in
        if let name = alert.textFields?.first?.text {        
            self.allContacts.append(self.contact)
        }
    }))


    self.present(alert, animated: true, completion: nil)
}

根据文档

,您似乎没有理解addTextField(configurationHandler:)

A block for configuring the text field prior to displaying the alert. This block has no return value and takes a single parameter corresponding to the text field object. Use that parameter to change the text field properties.

Link: https://developer.apple.com/documentation/uikit/uialertcontroller/1620093-addtextfield

您希望 self.contact 对象的 namesurname 在配置块中更新,但这永远不会发生。此 closure/block 仅用于配置文本字段,而不用于捕获用户输入。

在此闭包中,您可以修改文本字段 属性,例如占位符、背景颜色、边框等,以便在呈现之前对其进行配置。 但是如果你想捕获用户输入,使用动作闭包。

而是

alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (action) in
            if let name = alert.textFields?.first?.text,
                (alert.textFields?.count ?? 0) >= 1,
                let surname = alert.textFields?[1].text {
                self.contact.name = name
                self.contact.surname = surname
                self.allContacts.append(self.contact)
            }
        }))

希望对您有所帮助