从第一个 UIAlertController 打开第二个 UIAlertController

Open second UIAlertController from first UIAlertController

我们如何才能从第一个警报打开第二个 UIAlert?

第一段代码工作正常,显示了警报。但是我希望能够调用第二个警报视图,如果选择了第一个警报中的一个选项,就会出现该视图。

在下面的示例中,xcode 不喜欢在调用第二个警报的地方使用 "self",我不确定如何设置它。

带有白色感叹号的红色错误是“使用未解析的标识符'self'

有什么想法吗?

override func viewDidAppear(_ animated: Bool)
{
    super.viewDidAppear(animated)

    let firstAlert = UIAlertController(title: "Title", message: "some message", preferredStyle: .alert)
    firstAlert.addAction(UIAlertAction(title: "Option A", style: .default, handler: alert2() ))
    firstAlert.addAction(UIAlertAction(title: "Option B", style: .default, handler: nil))
    firstAlert.addAction(UIAlertAction(title: "Option C", style: .default, handler: nil))
    firstAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(firstAlert, animated: true)
}

func alert2(alert: UIAlertAction!) {
    //Put second alert code here:

    let secondAlert = UIAlertController(title: "Title", message: "some message", preferredStyle: .alert)
    secondAlert.addAction(UIAlertAction(title: "Option A", style: .default, handler: nil ))
    secondAlert.addAction(UIAlertAction(title: "Option B", style: .default, handler: nil))
    secondAlert.addAction(UIAlertAction(title: "Option C", style: .default, handler: nil))
    secondAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(alert2, animated: true)
}

你有两个错误,

第一个,您需要在 UIAlertController 名称而不是 UIAlertAction 名称中显示您的第二个警报

 self.present(secondAlert, animated: true)

不是方法名alert2

self.present(alert2, animated: true)

第二个,需要调用第一个alertcontroller UIAlertAction 完成处理程序方法像 alert2 而不是 alert2()

 firstAlert.addAction(UIAlertAction(title: "Option A", style: .default, handler: alert2 ))

完整答案

 override func viewDidAppear(_ animated: Bool)
{
    super.viewDidAppear(animated)

    let firstAlert = UIAlertController(title: "Title", message: "some message", preferredStyle: .alert)
    firstAlert.addAction(UIAlertAction(title: "Option A", style: .default, handler: alert2 ))
    firstAlert.addAction(UIAlertAction(title: "Option B", style: .default, handler: nil))
    firstAlert.addAction(UIAlertAction(title: "Option C", style: .default, handler: nil))
    firstAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(firstAlert, animated: true)
}

func alert2(alert: UIAlertAction!) {
    //Put second alert code here:
    let secondAlert = UIAlertController(title: "Title", message: "some message", preferredStyle: .alert)
    secondAlert.addAction(UIAlertAction(title: "Option A", style: .default, handler: nil ))
    secondAlert.addAction(UIAlertAction(title: "Option B", style: .default, handler: nil))
    secondAlert.addAction(UIAlertAction(title: "Option C", style: .default, handler: nil))
    secondAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(secondAlert, animated: true)
}