NSTimer
每隔一定时间执行某个函数
//创建定时器
//参数1.定时时间
//参数2.调用方法的对象
//参数3.定时时间到了自动调用的方法
//参数4.nil
//参数5.是否重复
NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(timmer), userInfo: nil, repeats: true)
实例:使用NSTimer实现帧动画
import UIKit
class ViewController: UIViewController {
var imageview = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
backImage()
creatUI()
//创建定时器
//参数1.定时时间
//参数2.调用方法的对象
//参数3.定时时间到了自动调用的方法
//参数4.nil
//参数5.是否重复
NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(timmer), userInfo: nil, repeats: true)
}
//MARK:定时器到时会调用的方法
func timmer() {
//改变图片的位置
//1.先拿到图片原来的位置
let frame = imageview.frame
imageview.frame = CGRectMake(frame.origin.x+10,frame.origin.y,121,96)
if frame.origin.x>self.view.bounds.width {
imageview.frame.origin.x = 0
}
}
//MARK:创建界面
//背景图片
func backImage() {
let imageview1 = UIImageView.init(image: UIImage.init(named: "back2.jpg"))
imageview1.frame = CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height)
self.view.addSubview(imageview1)
}
//搭建页面
func creatUI() {
imageview = UIImageView.init(image: UIImage.init(named: "DOVE 1"))
imageview.frame = CGRectMake(30,300,121,96)
self.view.addSubview(imageview)
//设置动画数组
var imageViewarr = [UIImage]()
for i in 1...18{
let image1 = UIImage.init(named: "DOVE \(i)")
imageViewarr.append(image1!)
}
imageview.animationImages = imageViewarr
imageview.animationDuration = 1
imageview.animationRepeatCount = 0
imageview.startAnimating()
}
}