Reputation: 71
I´m trying to update my @IBOutlet weak var gameclockLabel: UILabel!
from my class Gameclock
with delegate.
I have read and tested about a million different ways but can't make it work. I think that the more I read about it the more confused I get.
You can read more about what I'm trying to do here: swift invalidate timer in function
From the answers in that question I added this: var gameClock = Gameclock()
so I was able to start a function in class Gameclock
and first I tried to do the same with my class ViewController: UIViewController
but that didn't work so that's why I decided to try with delegate instead. Do you think delegate is the right way to go with this?
I'm going to add several timers in separate classes to this later on so perhaps there's a better way.
Would be nice if someone could point me in the right direction. At first I thought this would be not to complicated but seems I was mistaking :)
The complete code is as follows:
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()
}
}
Upvotes: 0
Views: 2661
Reputation: 114808
You haven't actually set your ViewController
instance as your GameClock
s delegate, so your updateLabel
method won't be called;
override func viewDidLoad() {
super.viewDidLoad()
gameclockLabel.text = "00:00"
self.gameClock.delegate=self
}
Upvotes: 3