首页 > 解决方案 > 在 SwiftUI ScrollView 中获取和设置内容的位置

问题描述

我有一个水平滚动视图,我想以编程方式设置一个位置。这是视图的主体:

let radius = CGFloat(25)
let scrollWidth = CGFloat(700)
let scrollHeight = CGFloat(100)
let spacing = CGFloat(20)
let circleDiameter = CGFloat(50)

...

    var body: some View {
        GeometryReader { viewGeometry in
            ScrollView () {
                VStack(spacing: 0) {
                    Spacer(minLength: spacing)

                    Circle()
                        .fill(Color.black.opacity(0.5))
                        .scaledToFit()
                        .frame(width: circleDiameter, height: circleDiameter)

                    ScrollView(.horizontal) {
                        Text("The quick brown fox jumps over the lazy dog. Finalmente.")
                            .font(Font.title)
                            .frame(width: scrollWidth, height: scrollHeight)
                            .foregroundColor(Color.white)
                            .background(Color.white.opacity(0.25))
                    }
                    .frame(width: viewGeometry.size.width, height: scrollHeight)
                    .padding([.top, .bottom], spacing)

                    Circle()
                        .fill(Color.white.opacity(0.5))
                        .scaledToFit()
                        .frame(width: circleDiameter, height: circleDiameter)

                    Spacer(minLength: spacing)
                }
                .frame(width: viewGeometry.size.width)
            }
            .background(Color.orange)
        }
        .frame(width: 324 / 2, height: spacing * 4 + circleDiameter * 2 + scrollHeight) // testing
        .cornerRadius(radius)
        .background(Color.black)
    }

如何更改此代码,以便我可以获取“The quick brown fox”的当前位置并在以后恢复它?我只是想做一些我们contentOffset在 UIKit 中一直做的事情。

我可以看到 aGeometryReader可能对获取内容的当前帧很有用,但是没有等效的编写器。为滚动视图或文本设置一个.position().offset()也没有让我在任何地方。

非常感激任何的帮助!

标签: uiscrollviewswiftui

解决方案


我一直在玩解决方案,并发布了一个要点,说明我在以编程方式设置内容偏移方面所做的工作 https://gist.github.com/jfuellert/67e91df63394d7c9b713419ed8e2beb7


推荐阅读