【问题标题】:Adding a segue to another view controller when specific action is picked from a popup当从弹出窗口中选择特定操作时,将 segue 添加到另一个视图控制器
【发布时间】:2019-10-07 15:49:32
【问题描述】:

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

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

我已经在 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)

    }

【问题讨论】:

    标签: ios swift popup alert


    【解决方案1】:

    你需要实现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)
    }
    

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

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

    【讨论】:

    • 好的!我添加了代码并编辑了 segue(谢谢,我想我现在理解得更好了),但是我的 d20alert.addAction yes 行出现错误,它指出:Cannot invoke 'addAction' with a argument list of输入“(UIAlertAction,@escaping()-> Void)”。知道这意味着什么/如何解决吗?
    • 动作返回方法有问题。检查编辑,现在应该可以正常工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2013-07-25
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多