Swift - Animate动态创建UIImageView

时间:2015-09-22 22:23:12

标签: ios swift uiimageview uiimage ios-animations

最初,当我只是动画我拥有的一个UIImageView时,我有这个代码工作。但随后我将其更改为动画创建的几个UIImageViews动画,但是因为它们是在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循环中的mapSprite不同。我怎样才能参考for循环中的那个然后为它制作动画?或者是否有更好的替代方案,我现在正在做什么?

非常感谢!

修改 使用Xcode 6.2

1 个答案:

答案 0 :(得分:0)

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

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 = $0["locationx"] as String
    var locationy = $0["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
    }
  }
}