SwiftUI ScrollView 滚动到相对位置

Isa*_*aak 4 scrollview horizontalscrollview swift swiftui scrollviewreader

我有一个很大的水平视图,不适合屏幕,所以我将其放入水平视图中ScrollView。如果 0 代表完全向左滚动,1 代表完全向右滚动 - 例如,我怎样才能滚动到相对位置 0.8?

因为我无法将 id 附加到子元素,所以ScrollViewReader似乎不起作用。

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.")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

jn_*_*pdx 19

您可以通过使用具有不可见背景视图的纯 SwiftUI 来解决此问题ZStack

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)
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)