我是编程和Swift的新手,并且一直跟随着教程学习。我正在学习MVC设计模式,并且具有一个可以在按下按钮时更改“标题”标签和“按钮”标签的功能。一旦到达故事1或故事2并选择了任何选项,我希望它重新启动到故事0和原始选择。但是,当故事更改为故事1时,choice2触发故事2,而当故事更改为故事2时,choice1触发故事1。我希望在选择任何选项后将其重置为Story 0。我尝试修改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)
}
答案 0 :(得分:1)
如果storyNumber i s 为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
}
}
我希望有帮助。
答案 1 :(得分:0)
希望我能正确理解您。您只想在到达故事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
}
}
希望这样的事情对您有用。就在我头顶上。