1,下面是一个简单的动画效果
使用 UIView.animateWithDuration() 给方块添加动画,让其在屏幕左侧与右侧间不断地来回运动。
.Autoreverse参数表示:动画运行到结束点后仍然以动画方式回到初始点(本例是x坐标)
.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()
}
}