Swift - 动画化动态创建的 UIImageView

Swift - Animate dynamically created UIImageView

最初,当我只是为我拥有的一个 UIImageView 设置动画时,我就使用了这段代码。但是后来我将其更改为为几个动态创建的 UIImageView 制作动画,但是由于它们是在 for 循环内动态创建的,所以我发现很难像最初那样为它们制作动画。

override func viewDidLoad() {
    super.viewDidLoad()

    var sprite: UIImage = UIImage(named: "sprites/areaLocatorSprite.png")!

    var locations:NSArray = animal[eventData]["locations"] as NSArray

    for var i = 0; i < locations.count; i++ {

        println(locations[i]["locationx"])
        var locationx = locations[i]["locationx"] as String
        var locationy = locations[i]["locationy"] as String

        let x = NSNumberFormatter().numberFromString(locationx)
        let y = NSNumberFormatter().numberFromString(locationy)
        let cgfloatx = CGFloat(x!)
        let cgfloaty = CGFloat(y!)

        var mapSprite: UIImageView
        mapSprite = UIImageView(image: sprite)

        mapSprite.frame = CGRectMake(cgfloatx,cgfloaty,10,10)
        townMap.addSubview(mapSprite)

        timer = NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: Selector("flash"), userInfo: nil, repeats: true)

    }

}

func flash() {
    var mapSprite:UIImageView?

    if mapSprite?.alpha == 1 {
        mapSprite?.alpha = 0
    } else {
        mapSprite?.alpha = 1
    }
}

这不起作用,因为 flash 函数中的 mapSprite 与 for 循环中的不同。我怎样才能在 for 循环中引用那个然后为它设置动画?或者会有比我目前正在做的更好的选择吗?

非常感谢!

编辑 使用 Xcode 6.2

您需要将视图存储到 属性 中,然后在每次触发计时器事件时枚举 属性

var sprites: [UIImageView]?

override func viewDidLoad() {
  super.viewDidLoad()

  var sprite = UIImage(named: "sprites/areaLocatorSprite.png")!

  var locations:NSArray = animal[eventData]["locations"] as NSArray

  self.sprites = map(locations) {
    var locationx = [=10=]["locationx"] as String
    var locationy = [=10=]["locationy"] as String

    let x = NSNumberFormatter().numberFromString(locationx)
    let y = NSNumberFormatter().numberFromString(locationy)
    let cgfloatx = CGFloat(x!)
    let cgfloaty = CGFloat(y!)

    var mapSprite = UIImageView(image: sprite)

    mapSprite.frame = CGRectMake(cgfloatx,cgfloaty,10,10)
    townMap.addSubview(mapSprite)

    return mapSprite
  }

  timer = NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: Selector("flash"), userInfo: nil, repeats: true)
}

func flash() {
  if let sprites = self.sprites {
    for sprite in sprites {
      sprite.alpha = sprite.alpha == 0 ? 1 : 0
    }
  }
}