![](/img/trans.png)
[英]how to update a property from ViewController in my another class(SWIFT)
[英]How can I get my Swift class to update the label in my viewcontroller in real time?
我正在使用Swift 2+,并正在做秒表/计时器。
基本上,我有一个类StopWatch2,可以从ViewController调用它。
我可以在类中启动,运行,停止和重置计时器。
我还可以使其更新ViewController中的标签,但仅适用于“ now”。 例如,如果我启动计时器,标签将显示7:59。 我可以在打印日志中看到计时器正在倒计时,但是它没有更新标签。 如果我单击“停止”,标签将以当前时间更新。
所有代码都在这里-https://github.com/markie1313/Debate-Timer 。 如果我需要发布代码示例,我将很高兴。
该怎么办?
标记
更新:
抱歉耽搁了。 这是我用于ViewController的代码
类ViewController2AC:UIViewController {var newTimer = StopWatch2()
@IBOutlet var timerText: UILabel!
@IBOutlet var startStopButton: UIButton!
@IBAction func startStopTimer(sender: AnyObject) {
timerText.text = "8:00"
newTimer.startStop()
timerText.text = newTimer.stopWatchString
}
override func viewDidLoad() {
super.viewDidLoad()
newTimer.minutes = 7
newTimer.seconds = 60
}
}
这里是被调用的函数:
func startStop() {
if startStopwatch == true {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateStopwatch"), userInfo: nil, repeats: true)
startStopwatch = false
startStopButtonExt = "Stop"
} else {
timer.invalidate()
startStopwatch = true
startStopButtonExt = "Start"
}
}
func updateStopwatch() -> String {
seconds -= 1
if seconds == 0 && minutes == 0 {
timer.invalidate()
labelText = "0:00"
return self.labelText
}
if seconds == 0 {
labelText = "\(minutes):00"
print(labelText)
minutes -= 1
seconds = 60
}
var secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
var minutesString = minutes > 9 ? "\(minutes)" : "\(minutes)"
if seconds == 60 {
secondsString = "00"
minutesString = "\(minutes + 1)"
}
stopWatchString = "\(minutesString):\(secondsString)"
labelText = stopWatchString
print("\(stopWatchString) test")
return self.stopWatchString
}
每次您view.setNeedsDisplay
操作主线程上的UI标签时,都必须调用view.setNeedsDisplay
。
您必须在updateStopwatch
方法的末尾更新标签文本:
timerText.text = labelText
我也建议您使用格式字符串,而不要使用number > 9
String(format: "%02d", myInt)
这会将前导零应用于您的数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.