Quando o usuário pressiona o botão para mostrar o retângulo, a animação de deslocamento do texto não deve ser substituída por .smooth(duration: 0.25) mas, em vez disso, continuar sua animação linear de 50 segundos.
Abaixo está o exemplo completo.
struct ContentView: View {
@State private var showingRect = false
var body: some View {
VStack {
Button("Show Rect") {
withAnimation(.smooth(duration: 0.25)) {
showingRect.toggle()
}
}
TextView()
if showingRect {
Rectangle()
.foregroundStyle(.blue)
.frame(width: 100, height: 100)
}
}
.padding()
}
}
struct TextView: View {
@State private var animate = false
var body: some View {
Text("This is a very long text. Yeah, it is very very long.")
.lineLimit(1)
.offset(x: animate ? -300 : 0)
.onAppear {
withAnimation(.linear(duration: 50)) {
animate = true
}
}
}
}
Use
.animation(nil, value: showingRect)
onTextView
para dizer que quandoshowingRect
muda,TextView
não deve ser animado.Se você ainda deseja que o texto seja animado para cima para caber no novo retângulo, adicione
.geometryGroup
:Use o
.transaction
modificador para isolar as animações. Use também o.animation
modificador para garantir que a animação do deslocamento do texto continue, evitando que a animação da visualização pai interfira.