Timerの生成とRun Loopの登録を別に行う方法です。
NSTimerは毎回作らないといけない模様 (使いまわそうとしても開始しなかった為)
---
import UIKit
class ViewController: UIViewController {
var count:Int = 0
var timer:NSTimer? = nil // タイマー
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
/*
timer = NSTimer(timeInterval: 0.01, // 繰り返し時間(秒)
target: self,
selector: (#selector(ViewController.DispWatchCount)), // ハンドラの指定
userInfo: nil,
repeats: true // 繰り返し
)
NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode)
*/
}
func update() {
print("timer")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var DispTime: UILabel!
@IBAction func stop(sender: AnyObject) {
timer?.invalidate()
}
@IBAction func ButtonStart(sender: AnyObject) {
timer = NSTimer(timeInterval: 0.01, // 繰り返し時間(秒)
target: self,
selector: (#selector(ViewController.DispWatchCount)), // ハンドラの指定
userInfo: nil,
repeats: true // 繰り返し
) // Timerを生成
NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode) // timerを開始 (Run Loopに登録)
}
@IBAction func ButtonStop(sender: AnyObject) {
timer?.invalidate() // timerを停止
}
// Timer handler
func DispWatchCount(){
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm:ss:SS"
let dispTime = formatter.stringFromDate(date)
/* メンバーにアクセスする場合
let calender = NSCalendar.currentCalendar()
let component = calender.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: date)
let dispTime = String(component.hour) + ":" + String(component.minute) + ":" + String(component.second)
*/
DispTime.text = dispTime
// count += 1
// DispTime.text = String(count)
}
}
0 件のコメント:
コメントを投稿