SwiftUI列表在底部添加空白间距

3
我希望能允许 SwiftUI List 滚动到最顶部,以使最后一个 Section 的标题位于 List 视图的顶部。我知道可以使用 GeometryReader 计算 List 的高度,并通过知道每个列表单元格的高度来计算应在列表底部添加多少空白空间以将其推上去。问题是,如果单元格例如扩展或具有灵活的大小,则此方法将无法正常工作。我想知道是否有一些我不知道的修饰符或更加“灵活”的方法来实现这一目标?
这是 List 的代码:
import SwiftUI

struct ListSections: View {
    var body: some View {
        List {
            Section(header: Text("Header 1")) {
                ForEach((0...10), id: \.self) { index in
                    Text("item \(index)")
                }
            }
            
            Section(header: Text("Header 2")) {
                ForEach((0...12), id: \.self) { index in
                    Text("item \(index)")
                }
            }
        }
    }
}

在下面的图片中,您可以看到左侧是默认情况下我可以滚动多远,右侧是我希望能够滚动多远。

enter image description here


你想让标题栏浮动起来,即使它的数据都向上滚动了吗?还是你也希望header1一起向上移动? - Tushar Sharma
你可以在最后一个部分下面尝试使用 Spacer().frame(height: 400)。但是,有一行额外的内容我无法弄清如何删除。 - aheze
@TusharSharma 我喜欢“粘性”标题,所以我希望Header 2能够将Header 1向上推(就像右侧截图中一样),并且Header 2能够固定在顶部。 - RealUglyDuck
@aheze,通过这样做,您将添加固定间距,即使我有更多的元素可以适应屏幕,它也会存在,而且只有在没有足够的元素将最后一个部分标题推到视图顶部时才存在。 - RealUglyDuck
1个回答

4

这里有两个选项: 选项1(首选方式) 只需向最后一个部分添加底部填充:

struct ListSections: View {
    var body: some View {
        List {
            Section(header: Text("Header 1")) {
                ForEach((0...10), id: \.self) { index in
                    Text("item \(index)")
                }
            }

            Section(header: Text("Header 2")) {
                ForEach((0...12), id: \.self) { index in
                    Text("item \(index)")
                }
            }
            .padding(.bottom, 300)
        }
    }
}

选项2: 在列表的最后一个部分之后添加视图即可解决问题。例如,我使用了一个颜色视图。

您的代码应该如下所示:

struct ListSections: View {
    var body: some View {
        List {
            Section(header: Text("Header 1")) {
                ForEach((0...10), id: \.self) { index in
                    Text("item \(index)")
                }
            }
            
            Section(header: Text("Header 2")) {
                ForEach((0...12), id: \.self) { index in
                    Text("item \(index)")
                }
            }
            
            Color(.clear)
               .frame(height: 300)
        }
    }
}

选项2在运行iOS 13的设备上崩溃。最好使用Rectangle() .frame(height: 300)。 - Yuvraj Bashyal
1
看起来选项1是将填充添加到所有子行而不是容器部分。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接