如何在 SwiftUI 中向列表添加页脚视图?

问题描述

我正在尝试将视图添加List底部,同时保持在安全区域内。这就是我想要的结果,我指的是“更新:凌晨 5:26”:

enter image description here

我尝试的是使用带有分隔符的 Section 页脚,但这不起作用:

struct ContentView: View {
    @State private var selectedTab = 0

    var body: some View {
        TabView(selection: $selectedTab) {
            List {
                Section {
                    Text("Item 1")
                    Text("Item 1")
                    Text("Item 1")
                }
                Section(
                    footer: vstack {
                        Spacer()
                        Text("Updated at: 5:26 AM")
                            .frame(maxWidth: .infinity)
                    }
                ) {
                    Text("Item 1")
                    Text("Item 1")
                    Text("Item 1")
                }
            }
            .listStyle(InsetGroupedListStyle())
            .tabItem {
                Label("First",systemImage: "alarm")
            }
            Text("Content 2")
                .tabItem {
                    Label("Second",systemImage: "calendar")
                }
        }
    }
}

enter image description here

然后我尝试使用 vstack 作为它自己的一部分,但也没有运气:

Spacer

enter image description here

我如何在考虑到 struct ContentView: View { @State private var selectedTab = 0 var body: some View { TabView(selection: $selectedTab) { List { Section { Text("Item 1") Text("Item 1") Text("Item 1") } Section { Text("Item 1") Text("Item 1") Text("Item 1") } vstack { Spacer() Text("Updated at: 5:26 AM") .font(.footnote) .foregroundColor(.secondary) .frame(maxWidth: .infinity) } .listRowBackground(Color(.systemGroupedBackground)) } .listStyle(InsetGroupedListStyle()) .tabItem { Label("First",systemImage: "calendar") } } } } 可能会滚动的同时实现这一点?我试图把它放在列表的末尾,而不是浮动。

解决方法

您可以将 ListText 一起放在 VStack 中而没有空格:

struct ContentView: View {
    @State private var selectedTab = 0

    var body: some View {
        TabView(selection: $selectedTab) {
            VStack(spacing: 0) {
                List {
                    Section {
                        Text("Item 1")
                        Text("Item 1")
                        Text("Item 1")
                    }
                    Section {
                        Text("Item 1")
                        Text("Item 1")
                        Text("Item 1")
                    }
                }
                .listStyle(InsetGroupedListStyle())
                Text("Updated at: 5:26 AM")
                    .font(.footnote)
                    .foregroundColor(.secondary)
                    .frame(maxWidth: .infinity)
                    .background(Color(.systemGroupedBackground))
            }
            .tabItem {
                Label("First",systemImage: "alarm")
            }
            Text("Content 2")
                .tabItem {
                    Label("Second",systemImage: "calendar")
                }
        }
    }
}