循环遍历 SKNode 的所有子节点? [英] Loop through all children of an SKNode?
问题描述
我有一个带有多个子 SKSpriteNode 的 SKNode.一个简化的例子:
I have an SKNode with a number of child SKSpriteNodes. A simplified example:
var parentNode = SKNode()
var childNode1 = SKSpriteNode()
var childNode2 = SKSpriteNode()
self.addChild(parentNode)
parentNode.addChild(childNode1)
parentNode.addChild(childNode2)
我想对所有这些孩子运行 colorizeWithColor
操作.当我在 parentNode
上运行该操作时,没有任何效果.
I want to run a colorizeWithColor
action on all of these children. When I run the action on parentNode
, there's no effect.
我不能在父级上使用 enumerateChildNodesWithName
,因为它的许多子级已经有了我正在使用的名称.
I can't use enumerateChildNodesWithName
on the parent, because many of its children already have names I'm using.
有没有办法循环遍历 parentNode
的所有子节点,以便对所有子节点运行单个操作?
Is there a way of looping through all children of parentNode
, in order to run a single action on all of them?
推荐答案
你可以简单地枚举parentNode.children
:
for child in parentNode.children as! [SKNode] {
// ...
}
如果有必要,检查每个孩子是否真的是一个SKSpriteNode
:
If necessary, check each child if it is actually a SKSpriteNode
:
for child in parentNode.children {
if let spriteNode = child as? SKSpriteNode {
// ...
}
}
从 Swift 2 (Xcode 7) 开始, 枚举和可选强制转换可以与带有 case-pattern 的 for 循环结合使用:
As of Swift 2 (Xcode 7), enumeration and optional cast can be combined with to a for-loop with a case-pattern:
for case let child as SKSpriteNode in parentNode.children {
// ...
}
这篇关于循环遍历 SKNode 的所有子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!