您的位置:首页 > 移动开发 > Swift

计时器Timer

2016-04-02 17:34 351 查看
最近在github看到30DaysofSwift这个项目,感觉想法很好,于是自己也跟着把上面的项目做了一下,也算是对自己近期来的学习的一个锻炼,这是第一个项目:计时器

主要实现了一个可以开始计数、暂停和重置功能的计时页面。原po主写的代码说是在swift2.1环境下写的,可是经我测验还是有问题,我写的代码在这里

运行截图如下:





这里说一下NSTimer的用法:

import UIKit
import Foundation

class ViewController: UIViewController {

@IBOutlet weak var lblSecond: UILabel!
var currentSecond = 0.0

var timer = NSTimer()

@IBAction func btnReset() {
timer.invalidate()
currentSecond = 0
lblSecond.text! = "0"
}

@IBAction func btnStart() {
timer = NSTimer(timeInterval: 0.01, target: self, selector: Selector("changeLblText"), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}

@IBAction func btnStop() {
timer.invalidate()
}

func changeLblText(){
currentSecond += 0.01
lblSecond.text! = String(format: "%.2f", arguments: [currentSecond])
}

}


NSTimer(timeInterval: 0.01, target: self, selector: Selector(“changeLblText”), userInfo: nil, repeats: true)的timeInterval参数是指selector的执行间隔,单位是秒,实例化的timer是用来每隔timeInterval执行target中的selector方法,并且是重复执行,当然,如果只实例化是不能执行的,timer的firing方法只能执行一次,所以将timer放到NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)中,这样就可以让NSRunLoop来执行它。timer的invalidate方法用来停止执行其任务。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  github swift uikit