2016-02-27 88 views
0

我想製作一個簡單的時鐘應用程序,其中冒號閃爍以使其看起來更好。我的代碼到目前爲止是:查看加載時啓動NSTimer

@IBOutlet weak var clockLabel: UILabel! 
var timerRunning = true 
var timer = NSTimer() 
var OnOff = 0 
var colon = ":" 
var hour = 0 
var minute = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 
    clockLabel.text = ("\(hour)\(colon)\(minute)") 
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "Counting", userInfo: nil, repeats: true) 
} 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 

func Counting(){ 
    if OnOff == 1 { 
    OnOff = 0 
    colon = ":" 
    clockLabel.text = ("\(hour)\(colon)\(minute)") 
    } 
    if OnOff == 0 { 
    OnOff = 1 
    colon = "" 
    clockLabel.text = ("\(hour)\(colon)\(minute)") 
    } 
} 

我想這樣工作的方式是,計時器開始於視圖加載的那一刻。我不想按一個按鈕來讓冒號開始閃爍。 在此先感謝

+0

你能詳細說明什麼是不準確的嗎?目前看起來定時器會在視圖加載時觸發,之後每秒重複一次...您的代碼對我來說看起來很好...... –

+0

您似乎在打開顯示器後立即關閉冒號。你希望打開和關閉多久? –

+0

「時鐘」部分丟失。你在哪裏設置「小時」和「分鐘」? – vadian

回答

1

我沒有看到任何問題與您的計時器(您的問題標題另有說明),據我可以告訴它應該在視圖加載後每秒觸發。

我注意到的一件事是您的代碼執行路徑中存在一個問題: 如果您更改變量(在第一個中),那麼兩個隨後的if語句重疊,請繼續閱讀以查看我的解決方案。

稍加改進我會做 - 爲OnOff變量似乎是在自然二進制 - 讓我們說一個boolean類型:

var colonShown : Bool = false // this is your "OnOff" variable (changed it to be more clear to the reader + made it boolean (you treat it as a boolean, so why not make it boolean?)) 

,然後在你的計時功能(我把它改名爲tick()):

// renamed your Counting() function, no particular reason for that (sorry if that causes confusion) -- you can replace your Counting() function with this one (also make sure to update your timer selector that references the "Counting()" function on each "tick") 
func tick(){ 
    colonShown = !colonShown // toggle boolean value 
    colon = colonShown ? ":" : "" // neat one-liner for your if statement 

    clockLabel.text = ("\(hour)\(colon)\(minute)") 

} 
+1

該解決方案更可讀[http://importblogkit.com/2015/03/writing-readable-code/]。優秀。 – nhgrif

+0

@nhgrif感謝您的輸入,非常感謝。 –

+0

非常感謝您的幫助。這工作出色。 –