arrays - 迭代 SKShapeNodes 数组

标签 arrays swift

苦苦思索如何遍历 SKShapeNode 数组。我似乎可以在 DidMoveToView() 中完成它,但不能在 WhenTouchesBegan() 中完成。

来自 GameScene.swift:

class GameScene: SKScene {
...
     var areaTwo = SKShapeNode()
     var areaThree = SKShapeNode()
     var areaFour = SKShapeNode()
     var currentArea = SKShapeNode()

//CGPaths as UIBezierPaths set here


     var areas = [SKShapeNode]()

    override func didMoveToView(view: SKView) {
...
          areaTwo = SKShapeNode(path: areaTwoPath.CGPath)
          areaThree = SKShapeNode(path: areaThreePath.CGPath)
          areaFour = SKShapeNode(path: areaFourPath.CGPath)
          let areas = [areaTwo, areaThree, areaFour]
...
//this works
          for area in areas {
               area.lineWidth = 4
                addChild(area)
          }
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */

        for touch in touches {
          let location = touch.locationInNode(self)
              currentArea.fillColor = UIColor.clearColor()

//this does not work! No errors thrown. Just doesn't seem to do anything.             
              for area in areas{
                   currentArea = area
                   if currentArea.containsPoint(location) {
                        currentArea.fillColor = UIColor.redColor()
               }
             }
         }
    }

令人沮丧的是,如果我使用一系列 if...else if...else if 我可以检查每个区域,但无法通过数组检查它们。

最佳答案

不太清楚你的目标。如果你只是想要一种迭代子节点的方法,你可以尝试

//init child nodes
for i in 1...2{
  let areaNode = SKShapeNode()
  ...
  areaNode.name = "area"
  parentNode.addChild(areaNode)
}

//iteration
for node in parentNode.children{
  if node.name == "area"{
    print("here we find a child area")
  }else{
    print("some irrelevant node found")
  }
}

顺便说一句,你的代码在 didMoveToView() 中工作的原因是你声明了一个新的 areas 数组,这实际上是一个方法内变量取代了上一类属性 areas

关于arrays - 迭代 SKShapeNodes 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39479037/

相关文章:

javascript - 如果 JSON 数组为 NULL,则返回 -1 仅适用于某些数据

javascript - jquery multitype 锯齿状数组表现奇怪

ios - Swift:触发 TableViewCell 以导致另一个 ViewController 中的 UIWebView 中的链接

iphone - 如何从 Storyboard 或快速在导航 View Controller 中添加默认后退按钮?

ios - Swift 如何在 UIImagepickercontroller 中为编辑器设置编辑器裁剪大小

c++ - 仅删除动态分配的结构对象数组的特定元素

java - 如何从使用数组构建的堆栈中删除元素?

ios - 在 iOS 中模拟标签栏

c 中带指针的 char 数组和 %s

ios - 如何仅在所有其他代码完成后才运行代码?