当应用程序打开时,我如何在用户输入的情况下一个接一个地打开两个警报



我正试图弹出两个警报,为一个应用程序输入两个玩家名称。我已经尝试在viewDidLoad和viewDidPear函数中使用AlertController代码。虽然其中一个在viewDidAppear中运行良好,但当调用第二个时会抛出错误,因为它继续运行其他代码。

理想情况下,我希望它弹出并说"输入玩家1的名字",给用户一个输入名字的机会,然后当按下提交时,在第二个警报上开始执行,这样它就会弹出"输入玩家2的名字"。

您需要为UIAlertAction实现一个处理程序,以便在其中显示另一个警报。看看这段代码:

let firstAlert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
firstAlert.addTextFieldWithConfigurationHandler({
    textField in
    textField.placeholder = "Some input"
})
let secondAlert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
secondAlert.addTextFieldWithConfigurationHandler({
    textField in
    textField.placeholder = "Some input 2"
})
firstAlert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: {
    action in
    print("text from first alert : + (firstAlert.textFields?[0].text)")
    self.presentViewController(secondAlert, animated :true, completion :nil)
}))
secondAlert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: {
    action in
    print("text from second alert : + (firstAlert.textFields?[0].text)")
}))

self.presentViewController(firstAlert, animated: true, completion: {
})

您可以使用这一行代码,例如在首次出现的UIViewController上的viewDidLoadviewDidAppear函数中。

希望它能帮助你