首页 > 解决方案 > 暂停代码,直到在 Swift 中获得 UIAlertController 的响应

问题描述

我一直试图从 UIAlertController 的用户那里得到答案。问题是在显示 UIAlertController 时代码仍在运行。我想显示警报,然后等到用户给出答案以继续代码。

func showPopUp(name:String)->String{
   var genre = ""
   let alert = UIAlertController(title: "What are you "+name+"?", message: nil, preferredStyle: .alert)

   alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
    genre = "Boy"
}))

   alert.addAction(UIAlertAction(title: "Girl", style: .default, handler: { action in
    genre = "Girl"
}))

   self.present(alert, animated: true)
   return genre
}

override func viewDidLoad() {
        super.viewDidLoad()
        print("This should appear before the alert")
        let a = showPopUp(name: "John)

        print("This should appear after the response")
        print("John is a "+a)
        [...more code using variable 'a' ...]


}

我不能将代码放在警报的操作中,因为它很长,而且它也在其他进程中运行。

标签: swiftxcodealertpause

解决方案


我无法将代码放入警报的操作中

是的,你可以,这是你必须做的。该操作您发出警报已被解除的信号(它还告诉您在警报中点击了哪个按钮)。您不必将代码本身放入操作中;您只需要调用该代码即可。

例子:

alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
    self.myVeryLongFunction(genre:"Boy")
}))

推荐阅读