UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

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.