Eri*_*ric 21 swiftui swiftui-list ios16 xcode14
当我们使用 SwiftUI List 组件并需要一个节标题时,顶部填充将出现在每个节的标题上。
iOS15下,我们用它UITableView.appearance().sectionHeaderTopPadding = 0
来解决这个问题。查看附件iOS15&Xcode14构建截图。
但在iOS16中,这个设置似乎不起作用。查看附件iOS16&Xcode14构建截图,滚动时:iOS16&Xcode14构建滚动。
所以,我的问题是如何在iOS16中删除节标题顶部填充,并且当滚动列表时,其节标题将被固定,就像附件iOS15&Xcode14构建滚动一样。
从iOS16开始,SwiftUI List组件似乎使用UICollectionView而不是UITableView,所以我尝试通过全局设置UICollectionView的section top padding来解决这个问题。不幸的是,我没有找到设置 UICollectionView 的部分顶部填充的方法。
我的代码如下。
//
// ContentView.swift
// ListIniOS16
//
// Created by Eric on 2022/07/23.
//
import SwiftUI
struct ContentView: View {
@State private var collections: [ListData] = ListData.collection
init() {
let appBarTheme = UINavigationBarAppearance()
appBarTheme.configureWithOpaqueBackground()
appBarTheme.backgroundColor = UIColor(.gray)
UINavigationBar.appearance().standardAppearance = appBarTheme
UINavigationBar.appearance().scrollEdgeAppearance = appBarTheme
if #available(iOS 15.0, *) {
// can fix sectionHeaderTopPadding issue in iOS15,
// but in iOS16 it doesn't work.
UITableView.appearance().sectionHeaderTopPadding = 0
}
}
var body: some View {
NavigationView {
VStack {
List {
ForEach(collections) { item in
Section(header: SectionHeader(title: item.group)) {
ForEach(item.rows) { row in
Text(row.name)
}
}
.listRowBackground(Color.gray.opacity(0.3))
}
}
.listStyle(.plain)
}
.navigationTitle("ListSectionHeader")
.navigationBarTitleDisplayMode(.inline)
}
}
struct SectionHeader: View {
let title: String
var body: some View {
ZStack(alignment: .leading) {
Color(.lightGray)
.frame(maxWidth: .infinity)
Text(title)
.font(.system(size: 16, weight: .bold))
.foregroundColor(.primary)
.padding(EdgeInsets(top: 10, leading: 18, bottom: 10, trailing: 18))
}
.listRowInsets(EdgeInsets())
}
}
}
struct ListData: Codable, Identifiable {
var id = UUID()
let group: String
let rows: [Row]
}
extension ListData {
static let collection: [ListData] = [.a, .b, .c]
static let a = ListData(group: "A", rows: [.row1, .row2, .row3])
static let b = ListData(group: "B", rows: [.row1, .row2, .row3, .row1, .row2, .row3])
static let c = ListData(group: "C", rows: [.row1, .row2, .row3, .row1, .row2, .row3, .row1, .row2, .row3])
}
struct Row: Codable, Equatable, Identifiable {
var id = UUID()
let name: String
}
extension Row {
static let row1 = Row(name: "Row1")
static let row2 = Row(name: "Row2")
static let row3 = Row(name: "Row3")
}
Run Code Online (Sandbox Code Playgroud)
非常感谢。
您可以从 UICollectionViews 中的部分标题中删除顶部填充,如下所示:
var layoutConfig = UICollectionLayoutListConfiguration(appearance: .plain)
layoutConfig.headerMode = .supplementary
layoutConfig.headerTopPadding = 0
let listLayout = UICollectionViewCompositionalLayout.list(using: layoutConfig)
UICollectionView.appearance().collectionViewLayout = listLayout
Run Code Online (Sandbox Code Playgroud)
编辑:不幸的是,我刚刚看到这会覆盖某些 SwiftUI 修饰符,例如.listRowSeparator()
或.onDelete()
。
归档时间: |
|
查看次数: |
5467 次 |
最近记录: |