SwiftUI字符串显示一个字符接一个字符



我需要一个提示,因为我不知道如何开始。我想在短延迟的情况下显示一个又一个字符串字符,但我不知道如何做到这一点。我应该把字符串转换成一个数组并在ForEach中显示这个数组吗?还是可以通过字符串操作来实现这一点?

感谢您的提示:-(Michael

这里有一个可以输入字符串的示例。它将把它变成一个字符串数组(针对每个字符(,并使用HStack和Text对象将它们添加到屏幕上。每个文本的初始不透明度为0.0,然后调用一个函数,该函数将在每个文本中循环,将不透明度设置为1.0。

struct CharView: View {

var characterArray: [String]
@State var characterLoopIndex: Int = -1
let loopDuration: Double = 0.5

init(input: String) {
characterArray = input.map { String($0) }
}

var body: some View {
HStack(spacing: 0) {
ForEach(characterArray.indices) { index in
Text("(characterArray[index])")
.opacity(characterLoopIndex >= index ? 1 : 0)
.animation(.linear(duration: loopDuration))
}
}
.onAppear(perform: {
startCharacterAnimation()
})
}

func startCharacterAnimation() {
let timer = Timer.scheduledTimer(withTimeInterval: loopDuration, repeats: true) { (timer) in

characterLoopIndex += 1
if characterLoopIndex >= characterArray.count {
timer.invalidate()
}

}
timer.fire()
}
}

用法:

CharView(input: "This is a test string")

最新更新