SwiftUI在列表下方添加视图

时间:2020-08-10 10:21:16

标签: swiftui

我有一些物品清单。

在列表下方,我想按一下以加载更多项目。 (由于加载所有项目都需要一些用户操作,例如输入TAN,因此,当用户滚动到列表的末尾时,不应自动执行此操作,而只有在他愿意时才这样做。)

我想要的是这样的视图:

enter image description here

但是,如果我将List和Button放在VStack中,则Button总是显示在屏幕底部,不仅是当我滚动到List的末尾:

struct ContentView: View {
    
    private let items = Range(0...15).map { "Item " + String($0) }
    
    var body: some View {
        VStack {
            List(items, id: \.self) { item in
                Text(item)
            }
            
            HStack {
                Spacer()
                
                Button("Load more") { print("Load more items") }
                
                Spacer()
            }
        }
    }
}

enter image description here

如果将按钮添加到列表中,则按钮显然会显示为具有白色背景且列表中没有空格的列表项:

struct ContentView: View {
    
    private let items = Range(0...15).map { "Item " + String($0) }
    
    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text(item)
            }
            
            HStack {
                Spacer()
                
                Button("Load more") { print("Load more items") }
                
                Spacer()
            }
        }.listStyle(GroupedListStyle())
    }
}

enter image description here

有什么方法可以添加一个视图,该视图在用户滚动到列表的末尾但不属于列表时变为可见? (或者至少看起来像在列表下方而不是列表的一部分?)

1 个答案:

答案 0 :(得分:2)

您应该使用第二种变体,但要进行一些调整,如下所示(颜色/空格会根据您的需要进行修改

demo

var body: some View {
    List {
        ForEach(items, id: \.self) { item in
            Text(item)
        }

        HStack {
            Button("Load more") { print("Load more items") }
        }
        .listRowInsets(EdgeInsets())
        .frame(maxWidth: .infinity, minHeight: 60)
        .background(Color(UIColor.systemGroupedBackground))

    }.listStyle(GroupedListStyle())
}