我有一些 Swift 代码来打印特定单词的每个字符 ("stackoverflow")
以及特定的延迟 (1.0s)
。
要理解我的想法,请看伪代码:
print("s")
wait(1s)
print("t")
wait(1s)
print("a")
wait(1s)
print("c")
wait(1s)
print("k")
wait(1s)
...
好的 - 您可以在下面找到我用 Swift 编写的代码:
var mystring="stackoverflow"
var counter=0.0
for i in mystring {
Timer.scheduledTimer(
timeInterval: Double(counter),
target: self,
selector: #selector(self.myfunc(_:)),
userInfo: String(i),
repeats: false)
counter=counter+1.0
})
}
<小时/>
func myfunc(_ timer: Timer) {
let value: String? = timer.userInfo! as? String
print ("Value: \(value as String?)")
}
但是如何在 for 循环完成后终止所有 myfunc
调用呢? 如何杀死我没有用变量声明的不同计时器以避免覆盖最后一个计时器?
最佳答案
为什么不一个计时器和几行附加逻辑。当计时器触发时,代码会打印字符串的第一个字符,然后删除第一个字符,直到字符串为空。最后计时器失效。
let string = "stackoverflow"
var temp = Substring(string)
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print(temp.prefix(1))
temp = temp.dropFirst()
if temp.isEmpty { timer.invalidate() }
}
或作为代码
let string = "stackoverflow"
var counter = 1
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print(string.prefix(counter))
if counter == string.count { timer.invalidate() }
counter += 1
}
关于ios - Swift:如何停止从循环开始的计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48127743/