Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

ios - Loop through all children of an 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)

I want to run a colorizeWithColor action on all of these children. When I run the action on parentNode, there's no effect.

I can't use enumerateChildNodesWithName on the parent, because many of its children already have names I'm using.

Is there a way of looping through all children of parentNode, in order to run a single action on all of them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply enumerate parentNode.children:

for child in parentNode.children as! [SKNode] {
    // ...
}

If necessary, check each child if it is actually a SKSpriteNode:

for child in parentNode.children {
    if let spriteNode = child as? SKSpriteNode {
        // ...
    }
}

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 {
    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...