当使用 ScrollViewReader 滚动到某个位置(例如宽度的 40%)时 - 当 ScrollView 的内容调整大小时,如何保留滚动位置?
我编写了一个小示例应用程序来说明问题:
最初,ScrollView 子级的宽度为 1600,滚动位置为 40%。当您单击“将宽度更改为 800”按钮时,子宽度将更改为 800 并且 ScrollView 滚动到末尾。我希望 ScrollView 在调整大小时保留滚动位置,或者在调整大小后始终滚动到 40%。
struct ContentView: View {
@State private var relativeScrollPosition: Double?
@State private var childWidth: CGFloat = 1600
var body: some View {
VStack {
Button("Change width to 800") {
childWidth = 800
}
Button("Change width to 1600") {
childWidth = 1600
}
RelativeScrollView(
relativeScrollPosition: $relativeScrollPosition,
childWidth: childWidth
) {
HStack{
ZStack {
Spacer().frame(height: 100).background(Color.green)
Text("1")
}
ZStack {
Spacer().frame(height: 100).background(Color.green) …
Run Code Online (Sandbox Code Playgroud) 有一种常见的处理滚动的方法,UICollectionView
这样当用户停止滚动时,它会逐渐减慢速度,并停止在集合视图中最近的项目与集合视图边界的边缘对齐的位置。
这与页面视图的不同之处在于,用户可以通过单次滑动快速滚动浏览连接视图中的多个项目,并且屏幕上会同时显示多个项目。
您可以在苹果自己的应用程序中看到这一点:电视、音乐、书籍和播客在每个各自的应用程序中浏览水平列表时都表现出这种行为。
使用UICollectionView
(或UIScrollView
,但在集合视图中更常见),通常使用该scrollViewWillEndDragging(scrollView:velocity:targetContentOffset:)
方法来实现,以检测用户何时停止滚动并为其提供要滚动到的更新的目标偏移量。
以下问题的最佳答案(作者:Rob Mayoff)详细描述了这一点:
我的问题:如何使用 SwiftUI 的 ScrollView 做到这一点?
我有一个水平 ScrollView,其中包含一个 HGrid,其中包含一组项目。我想实现一个类似于苹果应用程序中的水平浏览器。我可以使用 UICollectionView 来完成此操作,如上所述,但更喜欢在 SwiftUI 中“本地”执行此操作,而不包装 UICollectionView。
我希望使用 ScrollViewReader 和某种方式可以做到这scrollTo(_:anchor:)
一点,但它似乎没有任何东西可以满足这种需求。
这种行为是否可以使用 SwiftUI 本地实现,如果可以的话,如何实现?
scrollview uiscrollview uicollectionview 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 …
Run Code Online (Sandbox Code Playgroud) scrollview horizontalscrollview swift swiftui scrollviewreader
我正在寻找一种简洁的方法来识别 ScrollView 中当前可见的顶行。我希望 NavigationTitle 显示当前行号。有没有办法用 ScrollViewReader 来做到这一点,或者我必须用 GeometryReader 做些什么?在下面的代码中,我希望 myRowNumber 在用户上下滚动时更新。提前致谢。
struct ContentView: View {
let myArray: [Int] = [Int](1...100)
@State private var myRowNumber: Int = 50
var body: some View {
NavigationView {
ScrollView {
LazyVStack{
ScrollViewReader { proxy in
ForEach(myArray, id: \.self) { index in
Text("Row \(index)").id(index).font(.title)
}
.onAppear {
proxy.scrollTo(50, anchor: .top)
}
}
}
}
.navigationTitle("Current row = \(myRowNumber)")
}
}
}
Run Code Online (Sandbox Code Playgroud)