Swift 简单动画

384 阅读1分钟

简单的UIKit动画bounds:改变视图尺寸。 在ViewController中

 var fullSize = UIScreen.main.bounds.size
 var myLabel: UILabel!

定义不同的位置

let arrBounds = [CGSize(width: 100, height: 100),
CGSize(width: 50, height: 50), CGSize(width: 150, height:
150), CGSize(width: 50, height: 50)]

按下 bounds 按钮后执行动作的方法如下:

 func AnimateBounds() {
    let newSize = self.arrBounds[self.indexBounds]
    let originCenter = self.myLabel.center
    UIView.animateWithDuration(
      0.5, 
      animations: {
        self.myLabel.bounds = CGRect(
          x: 0, y: 0, 
          width: newSize.width, height: newSize.height)
        self.myLabel.center = originCenter
    })
    self.updateIndex("bounds")
}

目标尺寸newSize ,目前的位置originCenter,运用的第一个动画方法

UIView.animateWithDuration(_:, animations:)

Quick Help中的解释

第一个参数为动画执行的时间 ,单位为秒

第二个参数则是一个闭包( closure ), 将尺寸self.myLabel.bounds设置为前面取得的newSize,动画会在执行时间内,逐渐的改变尺寸。因为改变尺寸是以原点为准,所以 center 会变,再把 center 设置为原本的值originCenter。

最后使用self.updateIndex()方法來让值可以循环使用