¿Cómo animar el cambio de un texto a otro con la interfaz de usuario rápida?
Tengo una variedad de cadenas. Por ejemplo["Car", "Boat", "Van"]
¿Cómo anime el cambio del texto en la matriz (que puede contener más cadenas) para que cambie de Car
a Boat
a Van
borrando la transición? ¿Y para que continuamente repita esto?
Ya tengo una idea sobre cómo animar, pero me quedé atascado al cambiar el texto. He hecho la pregunta sobre por qué el texto no cambia aquí -> ¿Por qué el tamaño se anima y no el texto con esta vista SwiftUI?
Pero pensé que sería mejor escribir una pregunta separada sobre cómo cambiar realmente el texto.
Respuestas
Aquí hay una posible solución animando texto basado en una matriz. He usado la idea de transición de Asperis de esta solución aquí
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()
}
}
}
}
Ya he seleccionado la respuesta de @davidev. Pero según su respuesta, esto es lo que he implementado. Saludos 🍺
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
}
}
}
}
}