如何在 SwiftUI 中删除列表的左右填充?

How to remove the left and right Padding of a List in SwiftUI?

如何在SwiftUI中去除List的左右Padding? 我创建的每个列表都有一个单元格的前导和尾随边界。

我应该添加什么修改器来删除它?

修饰符是

.listRowInsets(EdgeInsets(......))

使用这个修饰符:

.listRowInsets(EdgeInsets(....))

但是,如 documentation 中所述,当在列表 中时,插图将应用于视图

Sets the inset to be applied to the view when placed in a list. (emphasis mine)

List 本身上使用此修饰符不会影响其中的视图。您必须在 List 内的 视图 上使用修饰符才能使修饰符生效。

用法示例:

List {
    Text("test")
        .listRowInsets(EdgeInsets(top: -20, leading: -20, bottom: -20, trailing: -20))
}

看起来 .listRowInsets 不适用于使用 content 初始化的 List 中的行。

所以这行不通:

List(items) { item in
    ItemRow(item: item)
        .listRowInsets(EdgeInsets())
}

但是这样做:

List {
    ForEach(items) { item in
        ItemRow(item: item)
            .listRowInsets(EdgeInsets())
    }
}
.listStyle(GroupedListStyle())

看来我们可以使用 PlainListStyle for List for iOS 14

List {
    Text("Row")
}
.listStyle(PlainListStyle())

你应该打电话给

.listRowInsets()

对于行,像这样:

List(items) {
            YoursRowView()
                .listRowInsets(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
        }

删除填充

iOS15,Xcode13

ScrollView {
    LazyVStack {
        ForEach(viewModel.portfolios) { portfolio in
            PortfolioRow(item: portfolio)
        }
    }
}

这使您可以完全控制列表(您也可以使用此代码删除分隔符)。 List 的当前实现不提供完全控制并包含一些问题。

注意这是一个完全不同的API。 ListLazyVStack 都是惰性容器,但与 List 相比,LazyVStack 不重用单元格,当行是更复杂的视图时,这将显着改变性能。

以上解决方案没有解决我的问题,因为我的列表有部分。

这为我解决了:

List {
    ForEach(years, id:\.self) { year in
        Section(header: SectionHeader(year)) {
            VStack(alignment:.leading) {
                ForEach(cars[year]!, id:\.self) { car in
                    ListItem(car)
                        .frame(width: UIScreen.main.bounds.size.width,
                               alignment: .center)
                        .listRowInsets(.init())
                }
            }
        }
        .frame(width: UIScreen.main.bounds.size.width,
               alignment: .center)
        .listRowInsets(.init())
        .listStyle(GroupedListStyle())
    }
}

在简历中,您必须重复该部分的命令。

import SwiftUI

struct ContentView: View {
    
    enum Flavor: String, CaseIterable, Identifiable {
        var id: String { self.rawValue }
        case sample1, sample2, sample3
    }
    var body: some View {
        VStack {
            GeometryReader { geometry in
                List {
                    ForEach(Flavor.allCases, id: \.self) { flavour in
                        Text(flavour.rawValue)
                            .frame(width: geometry.size.width,
                                   alignment: .leading)
                            .listRowInsets(.init())
                            .border(Color.red, width: 1)
                    }
                }
            }
        }
    }
}

绝对有效我测试过 请喜欢:-)