Skip to content

Commit e6304c6

Browse files
authored
Merge pull request #1 from foffer/master
Added ScrollViewReader to automatically scroll to new messages
2 parents d38082d + fbaeab5 commit e6304c6

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

Shared/ContentView.swift

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,22 @@ struct MessageView: View {
9898
var body: some View {
9999
VStack(spacing: 0) {
100100
ScrollView {
101-
VStack(spacing: 12) {
102-
ForEach(0..<messages.count, id: \.self) { i in
103-
ChatBubbleView(message: messages[i], index: i)
101+
// Add the new scroll view reader as a child to the scrollview
102+
ScrollViewReader { scrollView in
103+
VStack(spacing: 12) {
104+
ForEach(0..<messages.count, id: \.self) { i in
105+
ChatBubbleView(message: messages[i], index: i)
106+
}
107+
}
108+
.padding()
109+
// Add a listener to the messages array to listen for changes
110+
.onReceive(messages.publisher) { _ in
111+
// Add animation block to animate in new message
112+
withAnimation {
113+
scrollView.scrollTo(messages.endIndex - 1)
114+
}
104115
}
105116
}
106-
.padding()
107117
}
108118

109119
TextField("iMessage", text: $message, onCommit: { self.sendMessage() })

0 commit comments

Comments
 (0)