Swift - 时间控制器NSTimer每隔一定时间执行某个函数

1,时间控制器NSTimer可以实现定时器功能,即每隔一定时间执行具体函数,可以重复也可以只执行一次。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import UIKit
class ViewController : UIViewController {
var timer: NSTimer !
override func viewDidLoad() {
super .viewDidLoad()
// 启用计时器,控制每秒执行一次tickDown方法
timer = .scheduledTimerWithTimeInterval(1,
target: self ,selector: Selector ( "tickDown" ),
userInfo: nil ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,repeats: true )
}
/**
*计时器每秒触发事件
**/
tickDown()
{
print "tick..." )
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}

2,如果要停止定时器,调用NSTimer的invalidate()方法即可
1
timer.invalidate()


import UIKit


class ViewController: UIViewController {


@IBOutlet weak var textTf: UITextField!;

var timer: NSTimer!;

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view,typically from a nib.

timer = NSTimer(fireDate: NSDate.distantFuture(),interval: 1,target: self,selector: Selector("tickDown"),userInfo: nil,repeats: true);

NSRunLoop.mainRunLoop().addTimer(timer,forMode: NSDefaultRunLoopMode);

}


@IBAction func startTimer() {

if timer != nil {

timer.fireDate = NSDate.distantPast();

}

}

@IBAction func pauseTimer() {

if timer.valid {

timer.fireDate = NSDate.distantFuture();

}

}

@IBAction func stopTimer() {

if timer.valid {

timer.invalidate();

}

}

func tickDown() {

print("tickDown...");

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// dispose of any resources that can be recreated.

}


@IBAction func hiddenKeyborad(sender: AnyObject) {

viewClick();

}


@IBAction func viewClick() {

textTf.resignFirstResponder();

}

}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...