Swift:在 UIAlertAction 中设置变量值

标签 swift uialertcontroller uialertaction

我正在声明一个变量,然后尝试在 UIAlertAction 中设置它的值。当我在下面的代码中点击 “我要去那里” 按钮时,输出是:

1 thisCustomerRequesting: true

3 thisCustomerRequesting: false

你能告诉我为什么输出中缺少行 "2 thisCustomerRequesting: ..." 以及为什么 "3 thisCustomerRequesting: false" 是 false 而我期望它是真的。

var thisCustomerRequesting = false
if thisCustomerRequesting == false {
    let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "I am going there", style: .destructive, handler: {
        (alertAction1: UIAlertAction) in
            thisCustomerRequesting = true
            print("1 thisCustomerRequesting: \(thisCustomerRequesting)")
    }))
    alert.addAction(UIAlertAction(title: "Close", style: .default,handler: nil))
    self.present(alert, animated: true, completion: nil)
    print("2 thisCustomerRequesting: \(thisCustomerRequesting)")
}               
print("3 thisCustomerRequesting: \(thisCustomerRequesting)")

最佳答案

输出 2 应该在您的控制台中,但在 1 thisCustomerRequesting: true 之上。

输出 3 显示 3 thisCustomerRequesting: false 因为当用户按下按钮时 thisCustomerRequesting 被异步设置为 true
那时 print("3 thisCustomerRequesting:\(thisCustomerRequesting)") 已经被执行了。

关于Swift:在 UIAlertAction 中设置变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40287848/

相关文章:

ios - UIPageViewController冲突问题

swift - ReloadData不刷新列表

swift - 尝试快速移动 x 和 y 字段中的图像

xcode - 调用中的额外参数 'delay'

ios - 调用 UIAlertController 并等待用户交互

ios - 如何在 UIAlertController 中添加 UIImageView?

swift - 在 Swift 中制定隐私政策 : How to make UIAlertController action button disabled until message is scrolled to the bottom

ios - 警告 : UIAlertController is already presenting

ios - UIAlertController 操作表 whatsapp 样式

ios - 应用程序在后台运行时发送本地通知 Swift 2.0