设置最初可见的项目LazyGridswiftUI

问题描述

我正在尝试设置最初可见的项目LazyGrid(swiftUI)

这个主意不是将初始值设置为认值(0)

https://jsfiddle.net/nicyuvi/6xem7zgp/3/

初始值变成我选择的值,例如4

enter image description here

可以将网格移动到0和9。

我有简单的网格

import SwiftUI

struct ContentView: View {
    var body: some View {

        ScrollView(.horizontal,showsIndicators: false) {
          
            LazyHGrid(rows: [GridItem(.flexible(minimum: 200,maximum: 200))]) {
                ForEach(0 ..< 10){ val in

                    ZStack{

                    Rectangle()
                        .foregroundColor(.gray)
                        .frame(width: 200,height: 200)
                        
                        
                        Text("\(val)")
                            .fontWeight(.bold)
                            .font(.title)
                            .foregroundColor(.white)
                    }
                }
            }
        }
    }
}

解决方法

SwfitUI 2.0

ScrollViewReader用于此目的。我们为视图提供id,并通过滚动视图代理指定应显示哪个视图。

这是一个演示。经过Xcode 12 / iOS 14的测试

demo

struct DemoView: View {
    let initiail: Int = 4

    var body: some View {
        ScrollView(.horizontal,showsIndicators: false) {
            ScrollViewReader { sp in
                LazyHGrid(rows: [GridItem(.flexible(minimum: 200,maximum: 200))]) {
                    ForEach(0 ..< 10,id: \.self){ val in

                        ZStack{

                        Rectangle()
                            .foregroundColor(.gray)
                            .frame(width: 200,height: 200)


                            Text("\(val)")
                                .fontWeight(.bold)
                                .font(.title)
                                .foregroundColor(.white)
                        }.id(val)
                    }
                }.onAppear { sp.scrollTo(initiail) }
            }
        }
    }
}