微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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();

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐