首页 > 解决方案 > 如何使 SwiftUI 列表行背景颜色扩展整个宽度,包括安全区域之外

问题描述

在 SwiftUIList中,如何使列表行背景(通过设置.listRowBackground())扩展视图的整个宽度,即使在安全区域下也是如此?例如,在宽屏 iPhone(例如 iPhone 12 Pro Max)上横向运行时。目前,在安全区域开始之前,该单元格在单元格的最左侧显示为白色。

示例代码:

struct ContentView: View {
    var body: some View {
        List {
            Text("Test")
                .listRowBackground(Color(.systemGray3))
        }.listStyle(GroupedListStyle())
    }
}

这会产生如下所示的 UI。我希望单元格的灰色背景可以扩展设备的整个宽度。

我已经尝试添加.edgesIgnoringSafeArea(.all)到,Text但它没有任何区别。

在 iPhone 12 Pro Max 上横向运行的列表,单元格的最左侧显示为白色,与单元格的其余部分为灰色不同

标签: iosswiftswiftuiswiftui-list

解决方案


答案是放在.edgesIgnoringSafeArea([.leading, .trailing])背景Color本身,而不是列表项。

struct ContentView: View {
    var body: some View {
        List {
            Text("Test").listRowBackground(
                Color(.systemGray3).edgesIgnoringSafeArea([.leading, .trailing])
            )
        }.listStyle(GroupedListStyle())
    }
}

推荐阅读