我有一个字符串数组。例如["Car", "Boat", "Van"]
我如何动画更改数组中的文本(可以包含更多字符串),使其通过模糊过渡从Car
切换到Boat
再到Van
?所以它会不断地循环这个过程?
我已经有了一个如何动画的想法,但我被困在切换文本上。我问了一个问题,为什么文本不能在这里切换,-> Why does the size animate and not the text with this SwiftUI view?
但我认为写一个关于如何实际切换文本的单独问题可能会更好。
发布于 2020-12-14 00:57:46
这是一个基于数组的文本动画的可能的解决方案。我已经使用了这个解决方案here中的Asperis过渡思想。
struct ContentView: View {
var array = ["First", "Second", "Third"]
@State var shortString = true
@State var currentIndex : Int = 0
@State var firstString : String = ""
@State var secondString : String = ""
var body: some View {
VStack {
if shortString {
Text(firstString).font(.title).fixedSize()
.transition(AnyTransition.opacity.animation(.easeInOut(duration:1.0)))
}
if !shortString {
Text(secondString).font(.title).fixedSize()
.transition(AnyTransition.opacity.animation(.easeInOut(duration:1.0)))
}
}
.animation(.default)
.onAppear {
firstString = array[0]
secondString = array[1]
let timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { _ in
if (shortString) {
if currentIndex == array.count - 1 {
self.secondString = array[0]
currentIndex = 0
}
else {
self.secondString = array[currentIndex+1]
currentIndex += 1
}
}
else {
if currentIndex == array.count - 1 {
self.firstString = array[0]
currentIndex = 0
}
else {
self.firstString = array[currentIndex+1]
currentIndex += 1
}
}
shortString.toggle()
}
}
}
}
发布于 2020-12-14 02:02:39
我已经选择了@davidev答案。但根据他的回答,这就是我所实现的。干杯?
struct ContentView: View {
var array = ["First", "Second", "Third"]
@State var currentIndex : Int = 0
@State var firstString : String = ""
@State var timer: Timer? = nil
@State var isBlurred = false
var body: some View {
VStack {
Text(firstString).blur(radius: isBlurred ? 6 : 0)
}.onAppear {
self.timer = newTimer
}
}
var newTimer: Timer {
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { v in
let rndTime = [0.5, 0.3, 0.7, 1.0].randomElement()! // I wanted a random time up to 1 second.
v.invalidate()
currentIndex += 1
if currentIndex == array.count { currentIndex = 0 }
DispatchQueue.main.asyncAfter(deadline: .now() + rndTime) {
self.isBlurred.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.isBlurred.toggle()
firstString = array[currentIndex]
self.timer = newTimer
}
}
}
}
}
https://stackoverflow.com/questions/65282203
复制相似问题