.Repeat參數表示:動畫重復執行
import UIKit
class ViewController: UIViewController {
// 方塊
var block:UIView!
override func viewDidLoad()
{
super.viewDidLoad()
//創建方塊
block = UIView(frame:CGRectMake(0, 0, 25, 25))
block.center.y = self.view.bounds.height / 2 //方塊垂直居中
block.backgroundColor = UIColor.darkGrayColor()
self.view.addSubview(block)
//播放動畫
playAnimation()
}
//播放動畫
func playAnimation()
{
UIView.animateWithDuration(0.6, delay: 0.4, options: [.Repeat, .Autoreverse],
animations: {
self.block.frame.origin.x = self.view.bounds.width - self.block.frame.width
},
completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
2,添加多個大小不一的方塊,並設置動畫
方塊隨著尺寸變小,對應動畫逐級添加 delay 延時,看起來有種跟隨的效果。
import UIKit
class ViewController: UIViewController {
// 方塊
var block1:UIView!
var block2:UIView!
var block3:UIView!
override func viewDidLoad()
{
super.viewDidLoad()
//創建方塊
block3 = UIView(frame:CGRectMake(0, 0, 15, 15))
block3.center.y = self.view.bounds.height / 2 //方塊垂直居中
block3.backgroundColor = UIColor.darkGrayColor()
self.view.addSubview(block3)
block2 = UIView(frame:CGRectMake(0, 0, 20, 20))
block2.center.y = self.view.bounds.height / 2 //方塊垂直居中
block2.backgroundColor = UIColor.darkGrayColor()
self.view.addSubview(block2)
block1 = UIView(frame:CGRectMake(0, 0, 25, 25))
block1.center.y = self.view.bounds.height / 2 //方塊垂直居中
block1.backgroundColor = UIColor.darkGrayColor()
self.view.addSubview(block1)
//播放動畫
playAnimation()
}
//播放動畫
func playAnimation()
{
UIView.animateWithDuration(0.6, delay: 0.4, options: [.Repeat, .Autoreverse],
animations: {
self.block1.frame.origin.x =
self.view.bounds.width - self.block1.frame.width
},
completion: nil)
UIView.animateWithDuration(0.6, delay: 0.45, options: [.Repeat, .Autoreverse],
animations: {
self.block2.frame.origin.x =
self.view.bounds.width - self.block2.frame.width
},
completion: nil)
UIView.animateWithDuration(0.6, delay: 0.5, options: [.Repeat, .Autoreverse],
animations: {
self.block3.frame.origin.x =
self.view.bounds.width - self.block2.frame.width
},
completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}