【发布时间】:2019-09-17 03:38:30
【问题描述】:
我在其他一个问题中提出了这个问题,但我正在开发一款为 IOS 设计的基于文本的冒险游戏。
我正在做的事情之一是在特定情况下为按钮提供多种不同的功能。我在其他几篇文章中读到,我可以通过使用 swift 语句来实现这一点,并且我在改变动作方面取得了一些成功,但这不是正确的动作。
如下所示,我的大部分故事,以及给予玩家的选项,都存储在一个结构中,并且可以使用 PickStory 方法进行切换。
func mainStory()
{
Storys =
[Story(Story: "You are walking along a dirt path and come to a cross roads. You see a small shack just off the trail. What do you want to do?", Action: "Heal", North: true, South: true, East: false, West: false, storyProg: true, resultN: "You walk north and see a gate in the distance.", resultS: "Their is nothing to turn back for.", resultE: "", resultW: ""),
Story(Story: "You see a small gate at the end of the dirt path, and their is a gaurd standing infront of the gate.", Action: "Approach", North: true, South: true, East: true, West: true, storyProg: false, resultN: "", resultS: "", resultE: "", resultW: ""),
Story(Story: "You see a small well in the middle of town.", Action: "Attack", North: true, South: true, East: true, West: true, storyProg: false, resultN: "", resultS: "", resultE: "", resultW: "")]
PickStory()
}
func PickStory()
{
if Storys.count > 0
{
storyNum = 0
storyLabel.text = Storys[storyNum].Story
actionButton.setTitle(Storys[storyNum].Action, for: UIControl.State.normal)
adjustButtons(North: Storys[storyNum].North,
South: Storys[storyNum].South,
East: Storys[storyNum].East,
West: Storys[storyNum].West)
Storys.remove(at: storyNum)
}
else
{
NSLog("Done!")
}
}
现在虽然在 PickStory 方法中建立了 Action 按钮的文本,但实际操作在后面几行之后的实际按钮方法中发生了更改(请注意,打印语句只是临时占位符稍后会放置)。
@IBAction func actionButton(_ sender: Any)
{
switch Storys[storyNum].Action
{
case "Attack":
print("Attacking")
break
case "Heal":
print("Healing")
break
case "Approach":
print("Approaching")
break
default:
break
}
}
总结问题,文字会变成正确的动作,但实际动作不会改变。
我最初的猜测是,因为 actionButton 稍后出现,在 PickStory 方法之后,它会在删除索引后读取下一个故事。但是,如果不删除索引,我无法在故事中取得任何进展。
【问题讨论】:
-
storyNum是否在全球范围内声明?此外,您正在删除storyNum索引处的故事,所以也许这就是问题所在 - 当您在 switch 语句中检查它时它不存在。 -
@Chris 是的,但在代码中的其他任何地方都没有更改。它只是用来帮助切换语句。我也相信这可能是导致问题的原因。
-
我不太明白
adjustButtons()做了什么。一种解决方案可能是将UIButton子类化并添加storyAction属性,然后可以在switch 语句中使用sender.storyAction访问该属性。 -
adjustButtons() 实际上只是一种允许在特定情况下启用/禁用不同按钮的方法。因此,如果玩家在走廊里,他们只能朝两个方向移动。
标签: ios swift switch-statement ibaction