UICollectionView容器填充边距

36

我想为一个UICollectionView的容器添加内边距,让它看起来四周都有10pt的内边距。因此,在实例屏幕上,从下面开始有10pt的内边距:

layout.minimumInteritemSpacing = layout.minimumLineSpacing = 10;

我正在使用UICollectionViewFlowLayout来布局单元格。我还尝试了一个“技巧”,在顶部添加了一个10pt 的视图,但内容似乎不会滚动通过视图,因为它们是分开的。输入图像描述

5个回答

82
请尝试将以下代码放置在viewDidLoad()中:
collectionView!.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

这将为collectionView的每个边添加填充。


PS:我知道这个问题已经存在一段时间了,但它可能会对某些人有帮助;)


3
非常感谢,这个方法有效。应该将它标记为答案! - Crashalot

6

这是一个分页视图(垂直方向)。使用插入设置部分标题只会影响第一页。还有其他想法吗? - nmock

1
我使用了UICollectionViewDelegateFlowLayout代理中的几种方法来实现我所需的功能。我试图为具有阴影的单元格添加“填充”,以确保它们具有“悬浮”的效果,而不是接触UICollectionView的边缘。
首先,调用sizeForItemAt indexPath方法并给单元格一个大小:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.width * 0.80, height: collectionView.bounds.height * 0.98)
}

然后,调用insetForSectionAt section方法,并设置单元格的插入值:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 20, left: 25, bottom: 20, right: 25)
}

0
如果您正在使用 UICollectionLayoutListConfiguration,似乎要在某些外观中获得较小的边距,则必须在部分级别上执行此操作,如下所示:
private func createLayout() -> UICollectionViewLayout {
   let layout = UICollectionViewCompositionalLayout() { (sectionIndex, layoutEnvironment) -> NSCollectionLayoutSection? in
        
        // Create a list configuration as usual
        var config = UICollectionLayoutListConfiguration(appearance: .sidebarPlain)
        config.headerMode = .supplementary
        
        // Change the section's contentInsets to adjust the side margins
        let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: layoutEnvironment)
        section.contentInsets.leading = 10
        section.contentInsets.trailing = 10
        return section
    }
    return layout
}

根据苹果的反馈(https://developer.apple.com/forums/thread/679863


0

如果您正在使用配置,请将contentInsetsReference设置为布局的配置,以便跟随layoutMargins,然后在collectionView本身上设置layoutMargins。

var config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
config.headerMode = .supplementary
        
let layout = UICollectionViewCompositionalLayout.list(using: config)
layout.configuration.contentInsetsReference = .layoutMargins
        
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
collectionView.layoutMargins = .init(top: 16, left: 64, bottom: 16, right: 64)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接