枚举Swift中的类成员



我正在使用Swift和SpriteKit

我有一门课:

class Button: SKShapeNode
{
}

我有一些按钮:

var button1 = Button()
var button2 = Button()

我已经使用了这些节点的".name":

button1.name = "button1"
button2.name = "button2"

所以通常情况下,我会用enumerateChildNodesWithName("button")枚举这些节点,但在这里,名称已经取了,所以我如何枚举我的所有按钮(使用类Button(?

您可以通过调用以//*为节点名的enumerateChildNodesWithName来枚举给定节点的所有子节点。这是苹果公司文档中的一个例子。

然后在块中检查节点的类型是否为Button,并相应地执行操作。

这样的东西:

myNode.enumerateChildNodesWithName("//*") { node, ptr in
    if node is Button {
        // do something here
    }
}

您可以使用节点的children属性:

var buttonNodes = node.children.filter { $0 is Button }

完整示例:

import UIKit
import SpriteKit
let node = SKNode()
class Button: SKNode {
}
let button1 = Button()
let button2 = Button()
let label = SKLabelNode()
node.addChild(button1)
node.addChild(button2)
node.addChild(label)
let buttons = node.children.filter { $0 is Button }
print(buttons.count) // buttons only has 2 elements, the button nodes!

最新更新