UICollectionView 顶部间距

UICollectionView Top spacing

我的 Swift Xcode 项目中的 UICollectionView 有问题 我检查了所有插图和边距,我尝试了 ViewController 的:“调整滚动视图插图”和许多其他东西,但是 none 确实以任何方式改变了这一点。

我想减少/删除 collectionView 中第一行单元格上方的顶部间距

我创建了一个示例项目来找到这个问题的 solution/fix,但还没有成功

这似乎是使用通过情节提要/界面生成器插入的集合视图时的问题,因为如果我在代码端添加集合视图就不会发生这种情况

这是我的视图控制器的代码:

import UIKit

struct CVData: Hashable {
    var name: String
    var value: String
}

class ViewController: UIViewController {
    
    @IBOutlet weak var myCollectionView: UICollectionView!
    var dataSource: UICollectionViewDiffableDataSource<Section, CVData>!
    var cvDataList: [CVData] = []
    enum Section {
        case main
    }
    var CVDataLabels: [String] = ["Label1:","Label2:","Label3:","Label4:","Label5:","Label6:","Label7:","Label8:"]
    var CVDataValues: [String] = []
    var snapshot: NSDiffableDataSourceSnapshot<Section, CVData>!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureCollectionView()
        buildData()
        // Do any additional setup after loading the view.
    }

    func configureCollectionView() {
        
        let layoutConfig = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
        let listLayout = UICollectionViewCompositionalLayout.list(using: layoutConfig)
        myCollectionView.collectionViewLayout = listLayout
        myCollectionView.isScrollEnabled = false
        let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, CVData> { (cell, indexPath, item) in

            var content = UIListContentConfiguration.cell()
            content.text = item.name
            content.textProperties.font.withSize(8.0)
            content.textProperties.font = UIFont.preferredFont(forTextStyle: .body)
            content.secondaryText = item.value
            content.prefersSideBySideTextAndSecondaryText = true
            content.textProperties.adjustsFontSizeToFitWidth = false
            cell.contentConfiguration = content
        }
        
        dataSource = UICollectionViewDiffableDataSource<Section, CVData>(collectionView: myCollectionView) {
            (collectionView: UICollectionView, indexPath: IndexPath, identifier: CVData) -> UICollectionViewCell? in
            
            // Dequeue reusable cell using cell registration (Reuse identifier no longer needed)
            let cell = collectionView.dequeueConfiguredReusableCell(using: cellRegistration,
                                                                    for: indexPath,
                                                                    item: identifier)
            // Configure cell appearance
            cell.accessories = [.disclosureIndicator()]
            
            return cell
        
    }
    }


    func buildData() {
        
        let cvDataList = [
            CVData(name: self.CVDataLabels[0], value: "value1"),
            CVData(name: self.CVDataLabels[1], value: "value2"),
            CVData(name: self.CVDataLabels[2], value: "value3"),
            CVData(name: self.CVDataLabels[3], value: "value4"),
            CVData(name: self.CVDataLabels[4], value: "value5"),
            CVData(name: self.CVDataLabels[5], value: "value6"),
            CVData(name: self.CVDataLabels[6], value: "value6"), //added 20210510
            CVData(name: self.CVDataLabels[7], value: "value7")
        ]
        
        // Create a snapshot that define the current state of data source's data
        self.snapshot = NSDiffableDataSourceSnapshot<Section, CVData>()
        self.snapshot.appendSections([.main])
        self.snapshot.appendItems(cvDataList, toSection: .main)

        // Display data in the collection view by applying the snapshot to data source
        self.dataSource.apply(self.snapshot, animatingDifferences: false)
    }
}

这是来自该 UICOllectionView 的尺寸检查器设置

非常感谢任何帮助

我没有使用过 UICollectionViewCompositionalLayout.list,所以这只是一些快速研究和实验的结果...

UICollectionLayoutListConfiguration 的默认 .headerMode.none ... 当使用 .insetGrouped 时会导致我们看到的“额外 space” .

奇怪的是,还有一个 headerTopPadding 属性,我们可能希望它在这里有所帮助。它的默认值是 0 ...但是这似乎只适用于 IS 一个 header 视图。

所以,如果我们为 header 设置 .headerMode = .supplementary 和 return 一个空的 UICollectionReusableView,我们可以去掉额外的 space:

现在,顶部 space 与默认 left/right 填充相同。

这是我在 header 视图中使用的内容:

class EmptyHeaderView : UICollectionReusableView {
    static let reuseIdentifier:String = "emptyHeaderView"
}

并对您的 configureCollectionView() 功能进行了三处修改:

func configureCollectionView() {
    
    var layoutConfig = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
    
    // 1
    // we're going to supply an "empty" header supplementary view
    layoutConfig.headerMode = .supplementary
    
    let listLayout = UICollectionViewCompositionalLayout.list(using: layoutConfig)
    
    myCollectionView.collectionViewLayout = listLayout
    myCollectionView.isScrollEnabled = false
    let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, CVData> { (cell, indexPath, item) in
        
        var content = UIListContentConfiguration.cell()
        content.text = item.name
        content.textProperties.font.withSize(8.0)
        content.textProperties.font = UIFont.preferredFont(forTextStyle: .body)
        content.secondaryText = item.value
        content.prefersSideBySideTextAndSecondaryText = true
        content.textProperties.adjustsFontSizeToFitWidth = false
        cell.contentConfiguration = content
    }
    
    dataSource = UICollectionViewDiffableDataSource<Section, CVData>(collectionView: myCollectionView) {
        (collectionView: UICollectionView, indexPath: IndexPath, identifier: CVData) -> UICollectionViewCell? in
        
        // Dequeue reusable cell using cell registration (Reuse identifier no longer needed)
        let cell = collectionView.dequeueConfiguredReusableCell(using: cellRegistration,
                                                                for: indexPath,
                                                                item: identifier)
        // Configure cell appearance
        cell.accessories = [.disclosureIndicator()]
        
        return cell
        
    }
    
    // 2
    // register a reusable supplementary view for the header
    myCollectionView.register(EmptyHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: EmptyHeaderView.reuseIdentifier)

    // 3
    // provider for header suppleentary view
    dataSource.supplementaryViewProvider = { (collectionView: UICollectionView, kind: String, indexPath: IndexPath) -> UICollectionReusableView? in
        if kind == UICollectionView.elementKindSectionHeader {
            if let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: EmptyHeaderView.reuseIdentifier, for: indexPath) as? EmptyHeaderView {
                return headerView
            }
        }
        fatalError("Something's wrong with the setup...")
    }
}