ios - Swift:如何停止从循环开始的计时器?

标签 ios swift

我有一些 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/

相关文章:

ios - Objective-C 解决函数重载

ios - 快速将自定义包对象序列化为 json 字符串到 Bool

javascript - 如何正确地退出一个函数?

ios - 为 UITableViewCells 使用一堆不同的类是否会严重影响性能?

ios - touchesBegan 语法错误 - 没有成员

ios - NSURL 使用 mailto : 抛出 nil 异常

ios - iOS 中是否有可用的垃圾收集器概念?

ios - 如何让 SnapKit 约束左右边缘?

swift - 如何回放录制的视频?

swift - swift 中的转换运算符