swiftswiftuiscrollviewhorizontalscrollviewscrollviewreader

SwiftUI ScrollView Scroll to Relative Position


I have a big horizontal view that doesn't fit on screen, so I put it into a horizontal ScrollView. If 0 would represent scrolled to the left completely and 1 to the right completely - How can I e.g. scroll to a relative position of 0.8?

Since I cannot attach an id to a child element ScrollViewReader doesn't seem to work.

struct ContentView: View {

    var body: some View {
        ScrollView(.horizontal) {
            Text("Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on.")
        }
    }
}

Solution

  • You can solve this in pure-SwiftUI by using a ZStack with invisible background views:

    struct ContentView: View {
        
        var body: some View {
            ScrollViewReader { reader in
                ScrollView(.horizontal) {
                    ZStack {
                        HStack {
                            ForEach(0..<100) { i in
                                Spacer().id(i)
                            }
                        }
                        Text("Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on.")
                    }
                }
                Button("Go to 0.8") {
                    withAnimation {
                        reader.scrollTo(80)
                    }
                }
            }
        }
    }