暂停for循环直到获得Swift中UIAlertController的响应

问题描述 投票:0回答:1

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

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

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

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

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

override func viewDidLoad() {
    super.viewDidLoad()
    print("This should appear before the alert")
    var characters: [String] = ["John", "Tom", "Martha"]
    for ch in characters{
       let a = showPopUp(name: ch)
       print(ch + " is a "+ a)
    }
}

我不能将代码放在警报的操作中,因为它在for循环中,因此它继续而不会获得性别。

swift for-loop alert pause
1个回答
1
投票

您需要使用完成处理程序,因为用户输入是异步发生的,因此您无法使用同步return返回它。

与您的问题无关,但您应该使用字符串插值而不是+来连接字符串。

func showPopUp(name:String, genderCompletion: @escaping (String)->()) {
    let alert = UIAlertController(title: "What are you \(name)?", message: nil, preferredStyle: .alert)

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

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

    self.present(alert, animated: true)
}

override func viewDidLoad() {
    super.viewDidLoad()
    let characters: [String] = ["John", "Tom", "Martha"]
    for ch in characters{
        showPopUp(name: ch, genderCompletion: { gender in
            print("\(ch) is a \(gender)")
        })
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.