有两个选择的数组让我只走了一半的路。

问题描述 投票:1回答:1

我想做这个故事,用户有两个选择。现在它只工作了一半,我只是不明白为什么它不改变按钮上的选择。基本上,它可以工作,直到第二个 if 声明。

let startOfStory = [
    Story(title: "You see a fork in the road", choice1: "Turn Left", choice2: "Turn Right"),
    Story(title: "You see a tiger", choice1: "Shout for help", choice2: "Play Dead"),
    Story(title: "You find a Treasure Chest", choice1: "Open it", choice2: "Check for Traps"),
]

var storyNumber = 0

override func viewDidLoad() {
    super.viewDidLoad()

    updateUI()
}

@IBAction func choiceMade(_ sender: UIButton) {

    let userAnswer = sender.currentTitle

    updateUI()

    if userAnswer == startOfStory[0].choice1 {
        storyLabel.text = startOfStory[1].title
    } else if userAnswer == startOfStory[0].choice2 {
        storyLabel.text = startOfStory[2].title
    }

    if userAnswer == startOfStory[1].choice1 {
        storyLabel.text = startOfStory[0].title
    } else if userAnswer == startOfStory[2].choice1 {
        storyLabel.text = startOfStory[0].title
    }
}

func updateUI() {
    storyLabel.text = startOfStory[storyNumber].title
    choice1Button.setTitle(startOfStory[storyNumber].choice1, for: .normal)
    choice2Button.setTitle(startOfStory[storyNumber].choice2, for: .normal)
}
ios swift xcode
1个回答
1
投票

你的价值 storyNumber 被卡在了0上,因为那是它的定义,而且我看到的任何地方都没有更新。

你应该更新 storyNumber 在每次决定后,确保故事的进展,还应该给你的 updateUI() 在您的 if 职能。

@IBAction func choiceMade(_ sender: UIButton) {

    let userAnswer = sender.currentTitle

    if userAnswer == startOfStory[0].choice1 {
        storyLabel.text = startOfStory[1].title
        storyNumber = 1
    } else if userAnswer == startOfStory[0].choice2 {
        storyLabel.text = startOfStory[2].title
        storyNumber = 2
    }

    if userAnswer == startOfStory[1].choice1 {
        storyLabel.text = startOfStory[0].title
        storyNumber = 0
    } else if userAnswer == startOfStory[2].choice1 {
        storyLabel.text = startOfStory[0].title
        storyNumber = 0
    }

    updateUI()
}
© www.soinside.com 2019 - 2024. All rights reserved.