我正在尝试制作一个函数,该函数接受数组内容并显示每个元素(文本),我正在使用swiftUI @State变量来存储消息,还尝试了环境对象变量来存储消息并在其中显示一个Text(“”)。当前该函数仅显示数组中的最后一条消息,仅将结束循环元素存储在数组中。
请让我知道如何一次显示每个消息
谢谢
@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))
}
}
您应该使用重复计时器,如果视图消失,您可以取消该计时器。
例如通过字符串旋转:
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
呼叫的“推销” ,而不是像您希望的那样每五秒钟运行一次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句