簡體   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