我正在寻找一种方法来删除 SwiftUI 列表中的顶部填充
借助 iOS 15,我们可以做到UITableView.appearance().sectionHeaderTopPadding = 0
然而,在 iOS 16 中,List 已通过 UICollectionView 重新实现
我找不到删除节标题顶部填充的方法
这是示例代码
import SwiftUI
struct TaskRow: View {
var body: some View {
Text("Task data goes here")
}
}
struct HeaderText: View {
var text:String
var body: some View {
Text(text)
.font(.system(.title3))
.fontWeight(.bold)
.foregroundColor(.primary)
}
}
struct ListWithSections: View {
init() {
if #available(iOS 15.0, *) {
UITableView.appearance().sectionHeaderTopPadding = 0
} else {
// Fallback on earlier versions
}
}
var body: some View {
if #available(iOS 16.0, *) {
List {
Section(header: HeaderText(text: "Section 1")) {
TaskRow()
TaskRow()
TaskRow()
}
Section(header: HeaderText(text: "Section 2")) {
TaskRow()
TaskRow()
TaskRow()
}
}
.scrollContentBackground(.hidden)
.background(Color.gray)
.listStyle(.plain)
} else {
List {
Section(header: HeaderText(text: "Section 1")) {
TaskRow()
TaskRow()
TaskRow()
}
Section(header: HeaderText(text: "Section 2")) {
TaskRow()
TaskRow()
TaskRow()
}
}
.background(Color.gray)
.listStyle(.plain)
}
}
}
iOS 16 和 iOS 15 之间的比较图片
我们可以通过 List Plain 样式来实现它吗?
更新:按照 @Yrb 建议使用 ListRowInset 将提供几乎相同的 UI。然而,当我们滚动时,我们有细微的差别
Here what scroll in ios15 looks like (what I want to achieve in ios16)
Here what scroll in ios16 looks like (with listRowInset as @Yrb suggested)
提前致谢。
此致。
自 iOS 13 以来,SwiftUI 已经对此进行了原生实现,但没有人谈论它,因为你可以到达并设置UITableView.appearance()
。您在 SwiftUI 中处理的是listRowInsets
以及 Apple 添加到节标题的填充。本质上,您所做的就是控制所有插图。这是一把双刃剑,因为您现在可以控制一切,您不能只设置一个而将其余的保留为默认值。
您会发现的一件事是,默认值已从 iOS 15 更改为 iOS 16,因此您无法使用相同的数字。在 iOS 16 中,您还需要设置defaultMinListHeaderHeight
in .environment
.
我还提取了您的部分以节省重复。
struct ListSecHeaderHeightView: View {
var body: some View {
List {
Section(header: SectionView(text: "Section 1")) {
Text("TaskRow")
Text("TaskRow")
Text("TaskRow")
}
Section(header: SectionView(text: "Section 2")) {
Text("TaskRow")
Text("TaskRow")
Text("TaskRow")
}
}
.scrollContentBackground(.hidden)
.environment(\.defaultMinListHeaderHeight, 0) // Only necessary in iOS 16. For 15, use 30
.background(Color.gray)
.listStyle(.plain)
}
}
struct SectionView: View {
let text: String
var body: some View {
HStack {
Text(text)
.font(.system(.title3))
.fontWeight(.bold)
.foregroundColor(.primary)
}
// Set it here.
// iOS 15:
// The top goes to -8 to cancel out the padding.
// The leading goes to 16 as you had the section in line with the rows.
// iOS 16:
// The top goes to -20.
// The leading goes to 20 as you had the section in line with the rows.
.listRowInsets(EdgeInsets(top: -8, leading: 16, bottom: 0, trailing: 0))
}
}
最后,请发布最低可重复示例。我们应该能够运行您发布的代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)