我正试图用委托人从我的@IBOutlet weak var gameclockLabel: UILabel!更新我的class Gameclock
我已经阅读和测试了大约一百万种不同的方法,但都不能成功。我想我读得越多就越困惑。
你可以在这里了解更多关于我要做的事情:
swift invalidate timer in function
从那个问题的答案中,我添加了这个:var gameClock = Gameclock()所以我可以在class Gameclock中启动一个函数,首先我尝试对我的class ViewController: UIViewController执行同样的操作,但这不起作用,所以我决定改为使用delegate。你认为委派代表是正确的做法吗?
稍后我将在单独的类中添加几个计时器,因此也许有更好的方法。
如果有人能给我指个正确的方向就好了。一开始我以为这不会很复杂,但似乎我错了:)
完整代码如下:

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()
}
}

最佳答案

实际上,您还没有将ViewController实例设置为GameClock的委托,因此不会调用您的updateLabel方法;

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

10-01 22:46