NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

iMessage ScrollView

Forums > SwiftUI

How do I get same behaviour for regular ScrollView as is in iMessages?

I mean if you reached top and load new messages, not single item is pushed down.

If I add any new item at the end index of the array, view does not pushing any items up and keep user scroll position. Hovewer when I add something at the start index, all items are pushing down.



Without any example code of what you have so far its difficult to advise correctly however a general approach to controlling position in a ScrollView would be something like this.

Firstly you'd need to define a namespace above your body property

@Namespace var messageBottom

then enclose your ScrollView in a ScrollViewReader and attach an onAppear and onChange modifier to the ForEach loop usually used for displaying messages similar to this

ScrollViewReader { proxy in
  ScrollView {
  VStack {
      // Your content here, ususally a ForEach
        .onAppear {
          withAnimation { proxy.scrollTo(messageBottom, anchor: .bottom) }
        .onChange(of: messages.count ) { count in // Change to the array name holding your messages
          if(count == messages.count) {
             withAnimation { proxy.scrollTo(messageBottom, anchor: .bottom) }

Hope this helps.


Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.