I'm facing an issue with SwiftUI where the animation doesn't seem to work as expected in a ScrollView. I've created a minimal, reproducible example with a list of messages, and I want to scroll to the bottom of the list with a smooth animation when a new message is added. However, the animation doesn't happen consistently or smoothly. What might be causing this problem, and how can I fix it?
I have a SwiftUI view that contains a ScrollView with a list of messages displayed in a chat-like interface. When a new message is added to the list, I want the view to automatically scroll to the bottom to show the latest message. To achieve this, I'm using the onChange modifier along with the proxy.scrollTo method, wrapped in a withAnimation block. However, the animation doesn't consistently work as expected.
import SwiftUI
struct ContentView: View {
@State private var chats = ["Message 1", "Message 2", "Message 3"]
var body: some View {
VStack {
ScrollViewReader { proxy in
ScrollView {
ForEach(chats, id: \.self) { message in
Text(message)
.padding()
.id(message)
.onChange(of: chats.count) { newCount in
if newCount > 0 {
withAnimation(.easeInOut(duration: 1.0)) {
proxy.scrollTo(chats.indices.last, anchor: .bottom)
}
}
}
}
}
}
}
}
}