2016-03-06 44 views
0

我試圖用代理從我的class Gameclock更新@IBOutlet weak var gameclockLabel: UILabel!。 我已閱讀並測試了大約一百萬種不同的方式,但無法使其工作。我認爲我讀得越多,我就越困惑。swift - 試圖用代理更新UILabel

你可以閱讀更多關於什麼我想在這裏做: swift invalidate timer in function

從這個問題,我添加了這個答案:var gameClock = Gameclock()所以我能夠在class Gameclock啓動功能,第一我試着對我的class ViewController: UIViewController也一樣,但那不起作用,所以我決定嘗試使用委託。你認爲委託是正確的方式嗎?

我將在稍後的單獨的類中添加多個定時器,因此可能有更好的方法。

如果有人能指出我的方向是正確的,那就太好了。起初我以爲這將是不復雜,但似乎我誤以爲:)

完整的代碼如下:

import UIKit 

protocol test1: class { 
func updateLabel() 
} 

class ViewController: UIViewController, test1 { 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    gameclockLabel.text = "00:00" 
} 

var gameClock = Gameclock() 
var startstopPushed: Bool = false 

@IBOutlet weak var gameclockLabel: UILabel! 
@IBOutlet weak var startstop: UIButton! 
@IBAction func startStopbutton(sender: AnyObject) { 

    if startstopPushed == false { 

     gameClock.startGameclock() 
     startstop.setImage(UIImage(named: "stop.png"), forState: UIControlState.Normal) 
     startstopPushed = true 
    } 
    else 
    { 
     gameClock.stopGameclock() 
     startstop.setImage(UIImage(named: "start.png"), forState: UIControlState.Normal) 
     startstopPushed = false 
    } 
} 
func updateLabel() { 
    print("updated") 
    gameclockLabel.text = gameClock.timeString 
} 
} 

class Gameclock : NSObject { 

var gameclockTimer = NSTimer() 
var timeString: String = "" 
var seconds = 0 
var minutes = 0 
weak var delegate: test1? 

func startGameclock() { 
    print("start") 
    gameclockTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateGameclock"), userInfo: nil, repeats: true) 
} 

func stopGameclock() { 
    self.gameclockTimer.invalidate() 
    print("stopp") 
} 

func updateGameclock() { 

    seconds += 1 
    if seconds == 60 { 
     minutes += 1 
     seconds = 0 
    } 

    let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)" 
    let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)" 

    timeString = "\(minutesString):\(secondsString)" 
    print(timeString) 

    delegate?.updateLabel() 
} 
} 

回答

2

您還沒有實際設置你的ViewController實例作爲GameClock小號代表,所以你的updateLabel方法將不會被調用;

override func viewDidLoad() { 
    super.viewDidLoad() 
    gameclockLabel.text = "00:00" 
    self.gameClock.delegate=self 
} 
+0

謝謝你的保羅!現在完美的作品:D –