首页 > 解决方案 > SwiftUI ScrollView 滚动到相对位置

问题描述

我有一个不适合屏幕的大水平视图,所以我把它放到了一个水平视图中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.")
        }
    }
}

标签: swiftswiftuiscrollviewhorizontalscrollviewscrollviewreader

解决方案


使用SwiftUI-Introspect,用于“从 SwiftUI 内省底层 UIKit 组件”,我们可以实现这一点。

这是它的完成方式,并附有一个Slider来证明它的工作原理:

struct ContentView: View {
    @State private var relativePosition: CGFloat = 0.5
    
    var body: some View {
        VStack {
            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.")
            }
            .introspectScrollView { scrollView in
                let width = scrollView.contentSize.width - scrollView.frame.width
                scrollView.contentOffset.x = relativePosition * width
            }
            
            let _ = relativePosition  // Needed to update view
            
            Slider(value: $relativePosition, in: 0 ... 1)
        }
    }
}

推荐阅读