Swift:简化菜单按钮逻辑 [英] Swift: Simplify menu button logic
问题描述
我在 Swift 中有一个游戏,其中我的每个关卡都是从基本 GameScene 类继承的单独类(对于我正在做的事情来说,这种方式要容易得多,不要评判我).我还有一个菜单,每个级别都有一个按钮.这是按钮加载关卡的方式:
I have a game in Swift where each of my levels is a separate class inherited from the base GameScene class (it's a lot easier this way for what I'm doing, don't judge me). I also have a menu which has a button for each level. This is how the buttons loads the level:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let t = touches.first {
let node = atPoint(t.location(in: self))
if let name = node.name {
let newScene: GameScene!
switch Int(name)! {
case 1:
newScene = Level1(size: frame.size)
case 2:
newScene = Level2(size: frame.size)
case 3:
newScene = Level3(size: frame.size)
case 4:
newScene = Level4(size: frame.size)
case 5:
newScene = Level5(size: frame.size)
case 6:
newScene = Level6(size: frame.size)
case 7:
newScene = Level7(size: frame.size)
default:
newScene = Level1(size: frame.size)
}
view?.presentScene(newScene, transition: .crossFade(withDuration: 0.5))
}
}
}
对我来说,这个开关看起来非常丑陋和毫无意义,但我想不出避免它的方法.我希望这里有人能帮我解决这个问题,我只是想不出更好的选择.
To me, this switch looks incredibly ugly and pointless, but I can't think of a way to avoid it. I was hoping someone here could help me out with this, I just can't think of a better alternative.
推荐答案
您可以先将关卡的类名构造为字符串 "Level\(name)"
,然后再获取您需要的实际类通过将其名称传递给函数:
You could construct your Level's class name as a string "Level\(name)"
first and then get the actual class you need by passing it's name to the function:
func classFromString(_ className: String) -> AnyClass! {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!
return cls
}
使用示例:
let className = "Level1"
let levelInstance = (classFromString(className) as! GameScene).init(size: frame.size)
...当然最好的建议是避免这种架构
... but of course the best advice would be to avoid such kind of architecture
这篇关于Swift:简化菜单按钮逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!