SwiftUI ScrollViewReader scrollTo not scrolling to end of horizontal scroller with a text view

258 Views Asked by At

I have the below code.

The weird part: This method works perfectly as intended... as long as I nudge the scroll. It needs only what seems to be a pixel width scroll and then proceeds to work perfectly.

I get the feeling this is a swiftui bug or maybe i'm doing it a dumb way.

Thanks for the help.

ScrollViewReader { scrollProxy in
    ScrollView(.horizontal, showsIndicators: false) {
        VStack {
            Text(text)
                .id(0)
                .foregroundColor(.white)
                .font(.system(size: fontSize , design: .rounded))
            Spacer()
        }
    }
    .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
    .onChange(of: text) { _ in
        scrollProxy.scrollTo(0, anchor: .trailing)
    }
    .padding([.horizontal, .top])
}

P.S. Removing the VStack/Spacer makes no difference to the issue. Same with scollBounceBehavior.

1

There are 1 best solutions below

0
On BEST ANSWER

I found it!

The text needs to be placed in a foreach like so:

ForEach(Array(text.enumerated()), id: \.offset) { i, v in

but then, the id is not updated before the onchange proxy scoll is called so it does not scroll. I am trying to think of a better way to solve this but at least I know why it's not working.