swift 如何在iOS16中设置UICollectionLayoutListConfiguration时删除头

wfsdck30  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(129)

当我有一个包含节和列表组件的视图时,它为每个节都有一个顶部填充。

struct NewListView: View {

@State private var list = ["1", "2", "3", "4"]

var body: some View {
  NavigationView {
    List {
      ForEach(list, id: \.self) { item in
        let isHeaderHidden = item != "1"
        if isHeaderHidden {
          Section(header: Text("\(item)")) {
            Text("Content with Header")
          }.onAppear {
            print("item\(item)")
          }
        } else {
          Text("Content without header")
        }
      }
    }
    .listRowInsets(EdgeInsets())
    .listStyle(.plain)
    .navigationTitle("NavTitle")
    .navigationBarTitleDisplayMode(.inline)
  }
 }
}

字符串


的数据
为了删除填充,我设置了UICollectionLayoutListConfiguration(.headerTopPadding = 0),如下所示,但头视图出现在我不需要的部分(第一部分)。
我怎样才能删除标题,但也删除顶部填充在同一时间?
先谢谢你。

init() {
if #available(iOS 16, *) {
  var configuration = UICollectionLayoutListConfiguration(appearance: .plain)
  configuration.headerMode = .supplementary
  configuration.headerTopPadding = 0

  let layout = UICollectionViewCompositionalLayout.list(using: configuration)
  UICollectionView.appearance(whenContainedInInstancesOf: [UIViewController.self]).collectionViewLayout = layout
 }
}


cunj1qz1

cunj1qz11#

我通过创建一个自定义头视图解决了这个问题。

struct HeaderSectionView: View {
var title: String
let backgroundColor: Color
var body: some View {

let isHidden = title.isEmpty
if !isHidden {
  Rectangle()
      .listRowInsets(EdgeInsets())
      .frame(height: 28)
      .overlay(
          Text(title)
            .padding(.leading, 10), // You need this to add back the padding for the Text
          alignment: .leading
      )
} else {
  EmptyView()
    .frame(height: 0)
    .listRowInsets(EdgeInsets())
}

字符串
{\fnSimHei\bord1\shad1\pos(200,288)}
并为Section类应用了自定义标头。

Section(header: HeaderSectionView(title: section.title ?? "")) {

相关问题