Swift - 一个简单的动画效果(方块来回反复移动)
(本文代码已升级至Swift4)
1,下面是一个简单的动画效果
使用 UIView.animateWithDuration() 给方块添加动画,让其在屏幕左侧与右侧间不断地来回运动。.Autoreverse参数表示:动画运行到结束点后仍然以动画方式回到初始点(本例是x坐标)
.Repeat参数表示:动画重复执行



import UIKit class ViewController: UIViewController { // 方块 var block:UIView! override func viewDidLoad() { super.viewDidLoad() //创建方块 block = UIView(frame:CGRect(x:0, y:0, width:25, height:25)) block.center.y = self.view.bounds.height / 2 //方块垂直居中 block.backgroundColor = UIColor.darkGray self.view.addSubview(block) //播放动画 playAnimation() } //播放动画 func playAnimation() { UIView.animate(withDuration: 0.6, delay: 0.4, options: [.repeat, .autoreverse], animations: { self.block.frame.origin.x = self.view.bounds.width - self.block.frame.width }, completion: nil) } }
2,添加多个大小不一的方块,并设置动画
方块随着尺寸变小,对应动画逐级添加 delay 延时,看起来有种跟随的效果。



import UIKit class ViewController: UIViewController { // 方块 var block1:UIView! var block2:UIView! var block3:UIView! override func viewDidLoad() { super.viewDidLoad() //创建方块 block3 = UIView(frame:CGRect(x:0, y:0, width:15, height:15)) block3.center.y = self.view.bounds.height / 2 //方块垂直居中 block3.backgroundColor = UIColor.darkGray self.view.addSubview(block3) block2 = UIView(frame:CGRect(x:0, y:0, width:20, height:20)) block2.center.y = self.view.bounds.height / 2 //方块垂直居中 block2.backgroundColor = UIColor.darkGray self.view.addSubview(block2) block1 = UIView(frame:CGRect(x:0, y:0, width:25, height:25)) block1.center.y = self.view.bounds.height / 2 //方块垂直居中 block1.backgroundColor = UIColor.darkGray self.view.addSubview(block1) //播放动画 playAnimation() } //播放动画 func playAnimation() { UIView.animate(withDuration: 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.animate(withDuration: 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.animate(withDuration: 0.6, delay: 0.5, options: [.repeat, .autoreverse], animations: { self.block3.frame.origin.x = self.view.bounds.width - self.block2.frame.width }, completion: nil) } }