變數名稱 = NSTimer. scheduledTimerWithTimeInterval(時間間隔,target:self,selector:Selector("要呼叫的函數"),repeats:是否重覆)
以下是一個每隔1秒就會執行count++並顯示在Label上 ,按下按鈕可以停止NSTimer的程式
//
// ViewController.swift
// compoment
//
// Created by boywhy chen on 2016/12/19.
// Copyright © 2016年 boywhy chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mLabel: UILabel!
//宣告NSTimer物件
var timer:NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
//建立NSTimer,並以1秒間隔執行showCounter()
timer=NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.showCounter), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Counter函式
var count:Int = 0
func showCounter()
{
count++
mLabel.text = "\(count)"
}
//停止Timer Button Event
@IBAction func stopTimer(sender: AnyObject) {
timer?.invalidate()
timer = nil
}
}
執行畫面
沒有留言:
張貼留言