I have a SwiftUI related question. I’m trying to make a chat and make messages appear at the bottom of the screen (like at the screen from Telegram). All solutions I tried keep rendering messages at the top. Documentation and ChatGPT could solve my problem.
The thing I tried the first was to use defaultScrollAnchor(_ anchor:)
modifier to ScrollView
. That didn’t work and moreover I didn’t notice any changes using this modifier. Neither .top
, .center
, or .top
parameters didn’t change anything. I tried both on static and dynamic list of elements in ScrollView
. My code inside the ScrollView
looks like that:
ScrollView(showsIndicators: false) {
LazyVStack {
ForEach(viewModel.location.chat) { chat in
Text(chat.message)
.id(chat.id)
}
}
.frame(maxWidth: .infinity)
}
Then I tried to scroll to the bottom using onAppear{}
and onChange{}
modifiers with help of ScrollViewReader
and scrollTo(_ id:anchor:)
. That didn’t work either. As a last resort I’m asking this question here. Spacer()
didn’t work either. Here is my complete code for last implementation:
ScrollViewReader { proxy in
ScrollView(showsIndicators: false) {
LazyVStack {
ForEach(viewModel.location.chat) { chat in
Text(chat.message)
.id(chat.id)
}
}
.frame(maxWidth: .infinity)
}
.onAppear {
scrollToBottom(proxy: proxy)
}
.onChange(of: viewModel.location.chat) {
scrollToBottom(proxy: proxy)
}
}
And scrollToBottom
function:
private func scrollToBottom(proxy: ScrollViewProxy) {
DispatchQueue.main.async {
if let lastMessage = viewModel.location.chat.last {
proxy.scrollTo(lastMessage.id, anchor: .bottom)
}
}
}
user26646427 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.