如何将覆盖函数插入 if else 语句

2024-03-28

我意识到,使用基本逻辑,我无法将覆盖函数放入 if else 语句中,因为它会覆盖所有内容。但是我仍然需要放入 if else 语句来为 segue 做准备。因此,我正在工作的代码的工作方式是,如果用户点击按钮两次,他们就赢得了游戏,因此转到显示分数的获胜者视图控制器。如果他们输了,他们就会进入没有得分的视图控制器。所以我需要将覆盖函数segue放入updateTimer(), 在里面else if counter < 9.9 && level == 2 part.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let DestViewController : winViewController = segue.destination as! winViewController

    DestViewController.LebelText = labelx.text!

}

func updateTimer() {
    counter += 0.1
    labelx.text = String(format: "%.1f", counter)
    if counter > 10 && level < 2 {
        let next = self.storyboard?.instantiateViewController(withIdentifier: "loseViewController") as? loseViewController
        self.present(next!, animated: true, completion: nil)
    } else if counter < 9.9 && level == 2 {
        let nextc = self.storyboard?.instantiateViewController(withIdentifier: "winViewController") as? winViewController
        self.present(nextc!, animated: true, completion: nil)
    } else {
        return
    }
}

为了建立乔恩上面的评论,你甚至不应该打电话present(UIViewController:)- 它甚至不会调用prepare(for segue:)方法。听起来您想要做的是在特定时间检查条件,并根据该条件传递一些数据以呈现在目标视图控制器中。

如果你想使用 segues,最好的办法是设置一个 segue 标识符:

First, you need to create the segue. Hover over the view controller icon at the top of the VC in the Storyboard, then hold control and drag to the destination VC: createSegue

然后选择segue的类型

After that you need to set a unique identifier for the segue so you can differentiate between any other segues in your code. To do this, select the segue itself and then go to the inspector pane and type a unique name in the "Identifier" field: identifySegue

为您想要的两个 Segue 完成此操作后,您可以将代码编辑为如下所示:

func updateTimer() {
    counter += 0.1
    labelx.text = String(format: "%.1f", counter)
    if counter > 10 && level < 2 {
        // Use first unique segue identifier
        self.performSegue(withIdentifier: "identityA", sender: self)
    } else if counter < 9.9 && level == 2 {
        // Use second unique identifier
        self.performSegue(withIdentifier: "identityB", sender: self)
    }
}

现在你可以在里面添加特殊代码prepare(for segue:),并且您可以使用在 Interface Builder 中指定的唯一标识符来区分不同目标 VC 并为其添加特殊代码

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "identityA" {

        let destinationA: winViewController = segue.destination as! winViewController
        destinationA.LebelText = labelx.text

    } else if segue.identifier == "identityB" {

        let destinationB: loseViewController = segue.destination as! loseViewController
        destinationB.LebelText = labelx.text

    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将覆盖函数插入 if else 语句 的相关文章

随机推荐