Swift 如何创建具有延迟的for循环以每X秒显示一条消息?
我试图创建一个函数,它接受数组内容并显示每个元素文本, 我使用swiftUI@State变量来存储消息,我还尝试使用环境对象变量来存储消息并在文本中显示它们。当前,该函数仅显示数组中的最后一条消息,它仅在数组中存储结束循环元素 请让我知道如何一次延迟显示每条消息 谢谢Swift 如何创建具有延迟的for循环以每X秒显示一条消息?,swift,swiftui,Swift,Swiftui,我试图创建一个函数,它接受数组内容并显示每个元素文本, 我使用swiftUI@State变量来存储消息,我还尝试使用环境对象变量来存储消息并在文本中显示它们。当前,该函数仅显示数组中的最后一条消息,它仅在数组中存储结束循环元素 请让我知道如何一次延迟显示每条消息 谢谢 @State var messages = ["Welcome","FirstName","LastName"] @State var message = "" func DisplayMessageAnimation(mess
@State var messages = ["Welcome","FirstName","LastName"]
@State var message = ""
func DisplayMessageAnimation(messages: [String]) {
for i in 0..<messages.count {
// your code here
self.message = messages[i]
print(" message", self.message)
sleep(UInt32(5.0))
}
}
我想是这样的
for i in items {
do {
sleep(4)
}
// Your code here
}
您应该使用一个重复计时器,如果视图消失,您可以取消该计时器 例如,要在字符串中旋转:
import Combine
struct ContentView: View {
@State var message = "Hello, world!"
@State var timer: AnyCancellable?
var body: some View {
VStack {
Text(message)
Button(action: {
self.startRepeatingRotation(with: ["foo", "bar", "baz"])
}) {
Text("Start rotating messages")
}
}.onDisappear {
self.timer?.cancel()
}
}
private func startRepeatingRotation(with messages: [String]) {
guard !messages.isEmpty else { return }
var index = 0
self.message = messages[0]
self.timer = Timer.publish(every: 5, on: .main, in: .common).autoconnect().sink { output in
index = (index + 1) % messages.count
self.message = messages[index]
}
}
}
或者,如果您希望它在序列结束时停止,即非重复序列,可能:
private func startRotation(with messages: [String]) {
guard !messages.isEmpty else { return }
var index = 0
self.message = messages[0]
self.timer = Timer.publish(every: 5, on: .main, in: .common).autoconnect().sink { output in
index += 1
guard index < messages.count else {
self.timer?.cancel()
return
}
self.message = messages[index]
}
}
FWIW
永远不要“睡觉”。您永远不想阻塞主线程
您也不应该使用asyncAfter。如果您这样做了,那些计划的调度将留在那里,等待运行,即使您关闭了有问题的视图。如果时间间隔在将来很遥远,您将开始看到这些单独的asyncAfter调用的“聚合”,而不是像您希望的那样每五秒钟运行一次
计时器是个拙劣的建议。但是,您可以使用弱self改进异步调用,并且只安排1次下一次执行。重复计时器正是为这样的情况而设计的,您希望某些任务以一定的间隔重复。