首页 > 解决方案 > 当从弹出窗口中选择特定操作时,将 segue 添加到另一个视图控制器

问题描述

我正在尝试链接一个特定的视图控制器,该视图控制器将在用户从选择随机数后自动生成的不同弹出窗口中选择“是”时运行。

仅当用户选择是时,我将如何添加第二个视图控制器(并在用户选择否时丢弃弹出窗口)?

我已经在 Stack 上进行了研究,有人建议使用 Storyboard 和 Segues,所以我使用“Show Segue to Weapon Pop Up View Controller”连接了第一个和第二个视图控制器,第二个 VC 的故事板 ID 为“PopUp”。

谢谢你的帮助!

这是我的代码:

@IBAction func rolld20(_ sender: Any) {

        let randomnumber20 = Int.random(in: 1...20)
        d20label.text = String(randomnumber20)

        //create the alert
        let d20alert = UIAlertController(title: "You rolled a D20!",
        message: "You rolled a \(String(randomnumber20))! Is this enough?", preferredStyle: UIAlertController.Style.alert)

        // add the actions (yes/no buttons)
        d20alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil)) {
            //code to open up second view controller with the storyboard ID "PopUp" goes here I believe?
        }
        d20alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: nil))

        // show the alert when the user clicks to roll d20
        self.present(d20alert, animated: true, completion: nil)

    }

标签: iosswiftpopupalert

解决方案


您需要实施performSegueWithIdentifier.

在您的情况下,代码将类似于:

@IBAction func rolld20(_ sender: Any) {
    let randomnumber20 = Int.random(in: 1...20)
    let d20alert = UIAlertController(title: "You rolled a D20!",
    message: "You rolled a \(String(randomnumber20))! Is this enough?", preferredStyle: UIAlertController.Style.alert)
    d20alert.addAction(UIAlertAction(title: "Yes", style:  .default, handler: { (action) -> Void in
         self.performSegue(withIdentifier: "PopUp", sender: nil)
     }))
    d20alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: nil))
    self.present(d20alert, animated: true, completion: nil)
}

为了便于阅读,我删除了评论。请记住,identifier方法中的字符串与 SEGUE 标识符相关,而不是目标视图控制器标识符。要设置您的 segue 标识符,只需单击 segue:

在此处输入图像描述

并在“显示属性检查器”项上编辑标识符:

在此处输入图像描述


推荐阅读