John Sorensen
John Sorensen

Reputation: 960

Swift UI scrollTo proper anchor parameter

I'm working with scrollTo in a Swift UI project. Here's a visual of an example I've been using to understand the logic.

enter image description here

The example texts range from 0 to 99, with 99 being the last one and the one I am scrolling to. Note that the frame of example 99 extends below the bottom edge of the screen. How do I anchor the view such that the entire frame of 99 is visible? I'm guessing that this has to do with scrollTo's anchor parameter, but all the anchor values I've tried haven't seemed to do anything.

Here's my code:

import Foundation
import SwiftUI

struct Feed: View {
    var body: some View {
        ScrollView {
            ScrollViewReader { value in
                ForEach(0..<100) { i in
                    Text("Example \(i)")
                        .font(.title)
                        .frame(width: 200, height: 200)
                        .id(i)
                }
                .onAppear() {
                    value.scrollTo(99)

                }
            }
        }
    }
}

EDIT:

Some people in the comments pointed out that the Simulator renders the right output even if the Preview does not. Here is what the code looks like in the Simulator, with a black border added to highlight the frame:

enter image description here

Note that the frames don't extend past the bottom of the screen anymore.

Upvotes: 0

Views: 2436

Answers (1)

wakel
wakel

Reputation: 375

You have to call scrollTo from within withAnimation when using onAppear, otherwise scrolling behavior is very inconsistent.

Other than that, I always get good results with the .center anchor.

So in your case:

.onAppear() {
    withAnimation {
        value.scrollTo(99, anchor: .center)
    }
}

Upvotes: 2

Related Questions