标签未显示 Swift 中的计时器值
Label not showing value of timer in Swift
我有一个计时器循环,它执行基本的倒计时并将值打印到控制台。我试图将该值设置为标签的文本值。即使 Xcode 控制台显示计时器值的正确倒计时,应用程序中的标签仍显示 0。关于为什么会发生这种情况的任何想法?这是相关代码:
import UIKit
class GameViewController: UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var timerCount = 7
var timerRunning = false
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
self.timerCount = 7
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting"), userInfo: nil, repeats: true)
}
func Counting(){
timerCount = 7
do {
println(timerCount)
timerRunning = true
--timerCount
timerLabel.text = "\(timerCount)"
println(timerCount)
} while timerCount > 0
}
Counting() 方法错误。
你每秒都在启动计数方法,在该方法中你有一个循环更新 timerLabel.text,但是 UI 在 Counting() 完成之前不会更新......那就是为什么总是显示0。你只需要每秒减少计数并更新标签。
我想这就是你需要的:
func Counting(){
if timerCount == 0
{
timerCount = 7 // or self.timer.invalidate() in case you want to stop it
}
else
{
timerCount--;
timerLabel.text = "\(timerCount)"
println(timerCount)
}
}
希望对您有所帮助
我有一个计时器循环,它执行基本的倒计时并将值打印到控制台。我试图将该值设置为标签的文本值。即使 Xcode 控制台显示计时器值的正确倒计时,应用程序中的标签仍显示 0。关于为什么会发生这种情况的任何想法?这是相关代码:
import UIKit
class GameViewController: UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var timerCount = 7
var timerRunning = false
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
self.timerCount = 7
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting"), userInfo: nil, repeats: true)
}
func Counting(){
timerCount = 7
do {
println(timerCount)
timerRunning = true
--timerCount
timerLabel.text = "\(timerCount)"
println(timerCount)
} while timerCount > 0
}
Counting() 方法错误。
你每秒都在启动计数方法,在该方法中你有一个循环更新 timerLabel.text,但是 UI 在 Counting() 完成之前不会更新......那就是为什么总是显示0。你只需要每秒减少计数并更新标签。
我想这就是你需要的:
func Counting(){
if timerCount == 0
{
timerCount = 7 // or self.timer.invalidate() in case you want to stop it
}
else
{
timerCount--;
timerLabel.text = "\(timerCount)"
println(timerCount)
}
}
希望对您有所帮助