我是否可以使用 willSet 和/或 didSet 根据变量的值触发到新视图控制器的过渡



我是编程新手,今天我一直在研究 Swift 中的属性观察者。这让我想知道是否可以使用一个来触发应用程序在变量的值达到某个点时更改屏幕。

例如,假设我有一个使用变量"score"来保存和加载用户分数的游戏。我是否可以使用 willSet 或 didSet 根据分数将达到某个值的事实触发视图的变化?

我当时想的是使用这样的东西:

var maxscore : Int = 0 {
    didSet{
        if maxscore == 5{
        switchScreen()
        }}
}

。将调用开关屏幕函数。这应该有效吗?我无法找到有关此的任何信息,所以不知道这是因为这是不可能的还是我只是没有找到它。

但是我尝试,但没有成功。这一切都会编译和运行,但是当分数达到 5 这个神奇的数字时,什么也没发生。

为了完整起见,我的switchScreen函数代码如下:

func switchScreen() {
    let mainStoryboard = UIStoryboard(name: "Storyboard", bundle: NSBundle.mainBundle())
    let vc : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("HelpScreenViewController") as UIViewController
    self.presentViewController(vc, animated: true, completion: nil)
}

我用于将值设置为 5 的代码如下:

func CheckAnswer( answerNumber : Int)
{
    if(answerNumber == currentCorrectAnswerIndex)
    {
        // we have the correct answer
        labelFeedback.text = "Correct!"
        labelFeedback.textColor = UIColor.greenColor()
        score = score + 1
        labelScore.text = "Score: (score)"
        totalquestionsasked = totalquestionsasked + 1
        labelTotalQuestionsAsked.text = "out of (totalquestionsasked)"
        if score == 5 { maxscore = 5}
        // later we want to play a "correct" sound effect
        PlaySoundCorrect()
      }
    else
    {
        // we have the wrong answer
        labelFeedback.text = "Wrong!"
        labelFeedback.textColor = UIColor.blackColor()
        totalquestionsasked = totalquestionsasked + 1
        labelTotalQuestionsAsked.text = "out of (totalquestionsasked)"
        if score == 5 { maxscore = 5}
        // we want to play a "incorrect" sound effect
        PlaySoundWrong()
    }
    SaveScore()
    buttonNext.enabled = true
    buttonNext.hidden = false
}

这种方法在类内部,而不是你应该能够做到的!。检查这个答案!

//True model data
var _test : Int = 0 {
//First this
willSet {
    println("Old value is (_test), new value is (newValue)")
}
//value is set
//Finaly this
  didSet {
     println("Old value is (oldValue), new value is (_test)")
  }
}

最新更新