GO FURTHER, FASTER: Try the Swift Career Accelerator 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.

2      

Hi,

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) }
          }
        }
      }
      .id(messageBottom)
  }
}

Hope this helps.

2      

Hacking with Swift+

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and more!

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.