我正在开发适用于iPhone的计时器应用程序。但是当切换视图并返回初始计时器视图时,
label
未更新。虽然我可以看到它仍然在打印日志中运行。
我的viewDidLoad
中有以下代码。
当我再次进入label
视图时,如何重新开始刷新timer
?
另一种观点是通过Segue处理的。
func updateTime() {
var currentTime = NSDate.timeIntervalSinceReferenceDate()
//Find the difference between current time and start time.
var elapsedTime: NSTimeInterval = currentTime - startTime
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
println("----------")
println("currentTime")
println (currentTime)
println("elapsedTime")
println (elapsedTime)
println("extraTime")
println (extraTime)
println("summed")
println (summed)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
displayTimeLabel.text = "\(strMinutes):\(strSeconds)"
}
@IBAction func start(sender: AnyObject) {
if (!timer.valid) {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
}
@IBAction func stop(sender: AnyObject) {
timer.invalidate()
}
答案 0 :(得分:0)
我在选项卡视图应用程序中遇到了完全相同的问题,并使用NSNotification Center解决了它。为了使它适用于您的情况,您可以创建一个单独的函数来更新文本。
func updateText(notification: NSNotification) {
displayTimeLabel.text = "\(strMinutes):\(strSeconds)"
}
然后在你的" updateTime"函数,你有我拿出的行,用postNotifiction替换它:
NSNotificationCenter.defaultCenter().postNotificationName("UpdateTimer", object: nil)
然后将观察者放在View Controller中的ViewDidAppear函数中,文本应该更新:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(false)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateText:", name: "UpdateTimer", object: nil)
}
使用viewDidAppear中的观察者,始终会调用updateText函数,即使切换视图并返回,文本也会更新。