繁体   English   中英

我可以使用willSet和/或didSet来基于变量的值触发向新视图控制器的转换吗?

[英]Can I use willSet and/or didSet to trigger a transition to a new view controller based on the value of a variable?

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

例如,假设我有一个使用变量“得分”保存和加载用户得分的游戏。 我可以基于分数达到一定值的事实使用willSet或didSet触发视图更改吗?

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

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

        }}
}

...将调用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)")
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM