我在其他问题之一中提出了这个问题,但是我正在为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方法中建立了“操作”按钮的文本,但是实际操作在后面几行的实际按钮方法中进行了更改(请注意,打印语句只是以下方法的临时占位符:稍后放置)。
@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方法之后,它将在删除索引之后读取下一个故事。但是,如果不删除索引,我将无法获得整个故事的进展。
答案 0 :(得分:2)
您无法通过选择器操作发送参数,但可以将UIButton
子类化以添加自定义属性,该属性可以是任何东西。
import UIKit
class CustomButton: UIButton {
var storyAction: String
override init(frame: CGRect) {
self.storyAction = ""
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
self.storyAction = ""
super.init(coder: aDecoder)
}
}
可以在设置标题时设置此属性:
let action = Storys[storyNum].action // Customary to use lower case for instance properties and upper case for classes
actionButton.setTitle(action, for: UIControl.State.normal)
actionButton.storyAction = action
您可以在switch语句中对其进行检查。
@IBAction func actionButton(_ sender: CustomButton)
{
switch sender.storyAction
{
case "Attack":
print("Attacking")
break
case "Heal":
print("Healing")
break
case "Approach":
print("Approaching")
break
default:
break
}
}
请注意,我调用了属性storyAction
,以免与按钮的预先存在的action
属性发生冲突。
对所有enum
类型使用storyAction
而不是字符串可能更安全。这样可以更轻松地确保没有引起问题的拼写错误!
enum StoryAction {
case attack
case heal
case approach
}
可以根据需要扩展任意数量。使用case .attack
等来检入switch语句很容易。