【问题标题】:How do I return the next array when a button is pressed?按下按钮时如何返回下一个数组?
【发布时间】:2020-08-25 16:17:15
【问题描述】:

我是编程和 Swift 的新手,并且一直在学习教程。我正在学习 MVC 设计模式,并且我有一个功能可以在按下按钮时更改标题标签和按钮标签。一旦我们进入故事 1 或故事 2 并且我们选择了任何选项,我希望它重新启动到故事 0 和原始选择。但是,当故事更改为故事 1 时,选择 2 会触发故事 2,当故事更改为故事 2 时,选择 1 会触发故事 1。 I want it to reset to Story 0 when any choice is chosen.我试图修改 nextStory 函数但没有成功。任何帮助将不胜感激。!

型号:

struct StoryBrain {

    var storyNumber = 0

    let story = [Story(t: "You see a fork in the road.", c1: "Take a left.", c2: "Take a right."),
                 Story(t: "You see a tiger.", c1: "Shout for help.", c2: "Play dead."),
                 Story(t: "You find a treasure chest", c1: "Open it.", c2: "Check for traps.")
    ]

    func getStoryTitle() -> String {
        return story[storyNumber].title
    }

    func getChoice1() -> String {
        return story[storyNumber].choice1
    }

    func getChoice2() -> String {
        return story[storyNumber].choice2
    }

    mutating func nextStory(_ userChoice: String) {
        if userChoice == story[storyNumber].choice1 {
            storyNumber = 1
        } else if userChoice == story[storyNumber].choice2 {
            storyNumber = 2
        }


    }

}

视图控制器

@IBAction func choiceMade(_ sender: UIButton) {

        storyBrain.nextStory(sender.currentTitle!)
        updateUI()

    }

    func updateUI() {
        storyLabel.text = storyBrain.getStoryTitle()
        choice1Button.setTitle(storyBrain.getChoice1(), for: .normal)
        choice2Button.setTitle(storyBrain.getChoice2(), for: .normal)
    }

【问题讨论】:

  • 您遇到了什么问题?
  • 为什么不使用 Array[Dictionaries] 而不是 Story Object ?您将能够在每个项目中找到键,并根据键比较可以重置值

标签: ios swift model-view-controller


【解决方案1】:

如果 storyNumber is 0 然后检查选择更新下一个故事。
如果 storyNumber 不是 0,它可能是 1 或 2,您应该将故事重置为 0。

mutating func nextStory(_ userChoice: String) {
    if storyNumber == 0 {
        if userChoice == story[storyNumber].c1 {
            storyNumber = 1
        } else if userChoice == story[storyNumber].c2 {
            storyNumber = 2
        }
    } else {
        storyNumber = 0
    }
}

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    希望我理解正确。到达故事 2 后,您只想重新开始。

    mutating func nextStory(_ userChoice: String) {
        guard storyNumber != 0 else { storyNumber = 0; return }
    
            if userChoice == story[storyNumber].choice1 {
                storyNumber = 1
                return
            } else if userChoice == story[storyNumber].choice2 {
                storyNumber = 2
                return
            }
        }
    

    希望这样的东西适合你。就在我的脑海中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      相关资源
      最近更新 更多