ScrollView与Geometry Reader结合使用时无法正确滚动(弹跳)

时间:2020-11-11 13:47:15

标签: swiftui scrollview geometryreader

我已经在这里查看了答案(ScrollView Doesn't Scroll with Geometry Reader as Child),我猜这很相似,但是我无法弄清楚。

我的目标是显示大小相等(二次方)的图像。

这是我的观点:


struct MyGeoView: View {
    
    let icons = ["bed.double.fill","tram.fill","tv.music.note.fill","hare.fill", "person", "clock", "plus", "trash", "home", "arrow", "pencil", "scribble", "folder", "folder.circle", "trash.circle", "paperplane"]
    
    var body: some View {
        
        GeometryReader{ geo in
            ScrollView{
                GeometryReader{ geo in
                    LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 3 ){
                        ForEach(icons, id: \.self){ post in
                            Image(systemName: post)
                                .frame(width: geo.size.width/3, height: geo.size.width/3)
                                .background(Color.pink)
                                .foregroundColor(.white)
                        }
                    }
                }
            }
        }
    }
    
}

不幸的是,它无法正确滚动(弹跳),并且始终返回顶部。你有什么主意吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您只需要一个GeometryReader,外部一个。

此处为正确的代码。经过Xcode 12.1 / iOS 14.1的测试

var body: some View {
    GeometryReader{ geo in
        ScrollView{
            LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 3 ){
                ForEach(icons, id: \.self){ post in
                    Image(systemName: post)
                        .frame(width: geo.size.width/3, height: geo.size.width/3)
                        .background(Color.pink)
                        .foregroundColor(.white)
                }
            }
        }
    }
}