ios - 有两个选择的数组让我只完成了一半

标签 ios swift xcode

我正在尝试制作一个让用户有两种选择的故事。 现在它只能工作一半,我只是不明白为什么它没有改变按钮上的选择。 基本上它一直有效直到第二个 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)
}

最佳答案

您的 storyNumber 值停留在 0,因为这就是它的定义,并且在我能看到的任何地方都没有更新。

您应该在每次决定后更新 storyNumber 以确保故事进展,并且还应该在 if 函数之后调用您的 updateUI() 函数:

@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()
}

关于ios - 有两个选择的数组让我只完成了一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61394661/

相关文章:

iphone - 添加声音到 Xcode 4.3

ios - 在 UIScrollview Swift 中旋转 UIView

iphone - 使用 iPhone 应用程序进行表单注册

ios - 关闭模态视图 Controller

ios - UILabel 字体大小对于粗体字体不正确

ios - 使用 CocoaPods 和 Obj-C 桥接头

Swift 文本字段和值验证

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

ios - iPhone Messages 类似收件人 ListView

iOS - 无法在 bundle 中加载 NIB