Ios 如果我在代码中添加此函数,NSTimer会停止,为什么?
有2个Ios 如果我在代码中添加此函数,NSTimer会停止,为什么?,ios,loops,swift,Ios,Loops,Swift,有2个Arrays。第一个包含我要在UILabel上显示的Strings。第二个包含他们在UILabel上的等待时间 let items = ["stone","spoon","brush","ball","car"] let durations = [3,4,1,3,2] 和两个变量s,用于指定哪一个正在运行 var currentItem = 0 var currentDuration = 0 这是一个计时器系统: var timer = NSTimer() var seconds =
Array
s。第一个包含我要在UILabel
上显示的String
s。第二个包含他们在UILabel
上的等待时间
let items = ["stone","spoon","brush","ball","car"]
let durations = [3,4,1,3,2]
和两个变量
s,用于指定哪一个正在运行
var currentItem = 0
var currentDuration = 0
这是一个计时器系统:
var timer = NSTimer()
var seconds = 0
func addSeconds () {seconds++}
func setup () {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "addSeconds", userInfo: nil, repeats: true)
}
最后,这就是循环。回答:哪个数组
项在ui标签上停留了多少秒
问题
func flow () {
while seconds <= durations[currentDuration] {
myScreen.text = items[currentItem]
if seconds == durations[currentDuration]{
seconds == 0
currentItem++
currentDuration++
}
}
如果我改变这一点:
func addSeconds () {seconds++}
为此:
func addSeconds () {seconds++ ; flow () }
对于设置循环,什么都不会发生。即使是NSTimer,它也会在1秒停止。因为流方法有一个while循环,它永远不会退出并阻塞主线程,所以计时器永远不会启动 不要使用while循环。使用计时器触发的方法更新UI 因此:
您应该使用NSTimeInterval来计算经过的时间,但是如果我没有包含
flow()
函数,并且在addSeconds()
函数中说println(seconds)
,则没有任何问题,它正确地说秒。这就是您的想法。不要说var timer=NSTimer()
。只需说var timer:NSTimer代码>。你的版本创建了一个未使用的对象。@LeonardoSavioDabus好的,我已经更正了,但是你能解释一下区别吗?我没那么有经验。
func addSeconds () {seconds++ ; flow () }
func addSeconds () {
seconds++
myScreen.text = items[currentItem]
if seconds == durations[currentDuration] {
seconds == 0
currentItem++
currentDuration++
}
}