调整 UICollectionView 中特定部分的插图

Adjust insets of a specific section in UICollectionView

  1. insetForSectionAtIndex(在 DelegateFlowLayout 上)允许为一个部分中的所有单元格设置插图

  2. sectionInset(在 FlowLayout 上)允许设置适用于所有部分的插图。

但是,我正在寻找一种仅将插图应用于一个特定部分的方法 - 这可能吗?

您必须使用此方法为您的 class 实施 UICollectionViewDelegateFlowLayout

对于Swift4, 5+

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

    var edgeInsets = UIEdgeInsets()
    if section == THE_SECTION_YOU_WANT {
        // edgeInsets configuration stuff
    }

    return edgeInsets;
}

为Swift3

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

    var edgeInsets = UIEdgeInsets()
    if section == THE_SECTION_YOU_WANT {
        // edgeInsets configuration stuff
    }

    return edgeInsets;

}

for swift 4 被命名为:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
...

你会根据 UICollectionViewDelegateFlowLayout 协议做这样的事情:

func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {

        switch section {
        case 0:
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        case 1:
            return UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        }
    }