使用计时器更改 UILabel 的文本
change text of UILabel with timer
我想在一定时间后更改 UILabel 的文本。但在设定的时间后文本不会更改。我该如何解决这个问题?
查看我的代码:
var countDownText = "hello"
override func didMoveToView(view: SKView) {
startButton = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 90))
startButton.text = "\(countDownText)"
startButton.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height/2)
startButton.textColor = UIColor.darkGrayColor()
startButton.font = UIFont(name: "Arial", size: 20)
startButton.textAlignment = NSTextAlignment.Center
self.view?.addSubview(startButton)
countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc"), userInfo: nil, repeats: true)
}
func countDownFunc(){
theTime++
if(theTime >= 4){
countDownText = "testText"
}
if(theTime >= 8){
spawnEnemys()
startButton.removeFromSuperview()
countDownTimer.invalidate()
}
print(theTime)
}
提前感谢您的帮助:D
您的 countDownFunc
应该是:
func countDownFunc(){
theTime++
if(theTime >= 4){
countDownText = "testText"
startButton.text = countDownText
}
if(theTime >= 8){
spawnEnemys()
startButton.removeFromSuperview()
countDownTimer.invalidate()
}
print(theTime)
}
您的代码存在设计缺陷。
您更改了分配给视图控制器 countDownText
属性 的字符串,但这并没有同时更改标签的当前文本。
这里有一个简单的 playground 示例来说明问题:
import UIKit
var str = "Hello, playground"
var label = UILabel()
label.text = str
str = "Goodbye, playground"
print(label.text) // "Hello, playground"
如果您还想更新标签的文本,则需要更新其文本 属性,类似于您最初所做的:
startButton.text = "\(countDownText)"
这将更新标签的文本以匹配 countDownText
属性 的新值。
我想在一定时间后更改 UILabel 的文本。但在设定的时间后文本不会更改。我该如何解决这个问题?
查看我的代码:
var countDownText = "hello"
override func didMoveToView(view: SKView) {
startButton = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 90))
startButton.text = "\(countDownText)"
startButton.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height/2)
startButton.textColor = UIColor.darkGrayColor()
startButton.font = UIFont(name: "Arial", size: 20)
startButton.textAlignment = NSTextAlignment.Center
self.view?.addSubview(startButton)
countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc"), userInfo: nil, repeats: true)
}
func countDownFunc(){
theTime++
if(theTime >= 4){
countDownText = "testText"
}
if(theTime >= 8){
spawnEnemys()
startButton.removeFromSuperview()
countDownTimer.invalidate()
}
print(theTime)
}
提前感谢您的帮助:D
您的 countDownFunc
应该是:
func countDownFunc(){
theTime++
if(theTime >= 4){
countDownText = "testText"
startButton.text = countDownText
}
if(theTime >= 8){
spawnEnemys()
startButton.removeFromSuperview()
countDownTimer.invalidate()
}
print(theTime)
}
您的代码存在设计缺陷。
您更改了分配给视图控制器 countDownText
属性 的字符串,但这并没有同时更改标签的当前文本。
这里有一个简单的 playground 示例来说明问题:
import UIKit
var str = "Hello, playground"
var label = UILabel()
label.text = str
str = "Goodbye, playground"
print(label.text) // "Hello, playground"
如果您还想更新标签的文本,则需要更新其文本 属性,类似于您最初所做的:
startButton.text = "\(countDownText)"
这将更新标签的文本以匹配 countDownText
属性 的新值。