SwiftUI ScrollView scrollTo not consistently scrolling to latest message

I am implementing an AI chat application and aiming to achieve ChatGPT-like behavior. Specifically, when a new message is sent, the ScrollView should automatically scroll to the top to display the latest message.

I am currently using the scrollTo method for this purpose, but the behavior is inconsistent—sometimes it works as expected, and other times it does not. I’ve noticed that this issue has been reported in multiple places, which suggests it may be a known SwiftUI limitation.

I’d like to know:

Has this issue been fixed in recent SwiftUI versions, or does it still persist?

If it still exists, is there a reliable solution or workaround that anyone can recommend?

You can’t scroll to an item added in the same update; by the time you call scrollTo, the system don’t know about the new item.

The right way to do this is to use onChange so that SwiftUI enqueues a new update once the collection has propagated through. Like so:

struct ContentView: View {
    @State private var items = Array(0 ..< 20)
    var body: some View {
        NavigationStack {
            ScrollViewReader { proxy in
                List {
                    ForEach(items, id: \.self) { item in
                        Text("Row \(item)")
                            .onTapGesture {
                                proxy.scrollTo(item, anchor: .bottom)
                            }
                    }
                }
                .toolbar {
                    Button {
                        let newItem = items.count
                        items.append(newItem)
                    } label: {
                        Image(systemName: "plus")
                    }
                }
                .onChange(of: items.count) {
                    proxy.scrollTo(items.count-1, anchor: .bottom)
                }
            }
        }
    }
}

Let me know if this helps, and if you have any further questions please share a sample code that reproduces the issue. That'll be helpful in getting more context.

SwiftUI ScrollView scrollTo not consistently scrolling to latest message
 
 
Q