I am currently working on a SwiftUI chat interface where I display messages using a ScrollView and LazyVStack. I want the chat to always display the last message (i.e., scroll to the bottom) when a new message is received or when the view first appears. I know that ScrollViewReader is solution to this, but I'm not sure how to implement it correctly.
Here's my current code for the chat view:
struct ChatMessage: Identifiable {
let id: Int
let text: String
let isFromCurrentUser: Bool
}
struct ChatView: View {
var messages: [ChatMessage]
var body: some View {
ScrollView {
ScrollViewReader { scrollView in
LazyVStack(spacing: 20) {
ForEach(messages, id: \.id) { message in
HStack {
if message.isFromCurrentUser {
Spacer()
Text(message.text)
.padding()
.background(Color.gray.opacity(0.2))
.foregroundColor(.black)
} else {
Text(message.text)
.padding()
.foregroundColor(.black)
Spacer()
}
}
}
}
}
}
}
}
@Statevariable, for example,isOnBottomwhen it appears respectively when it disappears. Then, when new massages arrive (or change), scroll only whenisOnBottomis true. (of course, this is just an idea, needs to be confirmed with an actual implementation)