关于ios:在UICollectionView的每个边缘周围放置边距

Placing a margin around each edge of the UICollectionView

当UICollectionView填充了项目时,它们总是直接进入UICollectionView的边缘,如下所示:

1
2
3
4
5
6
7
8
---------------
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
---------------

我想在每个边缘周围放一个边距,如下所示:

1
2
3
4
5
6
7
8
---------------
| X X X X X X |
| X X X X X X |
| X X X X X X |
| X X X X X X |
| X X X X X X |
| X X X X X X |
---------------

我尝试通过将UICollectionView放置在其托管UIView中来实现此目的,方法是将其Frame设置为模拟边框,但它在Frame内滚动,因此在顶部和底部切断,滚动条也出现在框架的边界内。

我已经查看了API,但我看不到任何明显的实现这一点。 有任何想法吗?


我知道这是一个老问题,但不要忘记UICollectionView继承自UIScrollView。

1
2
UICollectionView *collectionView = [[UICollectionView alloc] init];
collectionView.contentInset = UIEdgeInsetsMake(x.x, x.x, x.x, x.x);
1
2
3
// Swift 3 for good measure
let collectionView = UICollectionView()
collectionView.contentInset = UIEdgeInsets(top: x.x, left: x.x, bottom: x.x, right: x.x)

请注意,contentInset和sectionInset都可能会更改视图中单元格的间距。有关更多信息,请参阅此文章。


您可以使用以下功能。

1
2
3
4
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  {
      return UIEdgeInsetsMake(50, 50,15,50);
  }

您将不得不使用该数字来弄清楚如何在一行中强制使用collectionviewCells。

1
UIEdgeInsetsMake ( CGFloat top,CGFloat left,CGFloat bottom,CGFloat right);

对于Swift 3

1
2
3
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(10, 4, 10, 4)
}


您可以使用collectionview的协议控制网格的各个方面。这是一个例子:

1
2
3
4
5
6
7
8
9
10
- (UICollectionViewFlowLayout *)collectionViewFlowLayout
{
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.itemSize = CGSizeMake(180, 255);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 30, 0, 30);
    flowLayout.minimumInteritemSpacing = 0.0f;
    flowLayout.minimumLineSpacing = 0.0f;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    return flowLayout;
}

你想要改变的是sectionInsets


1
2
(UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
}

你可以在左侧给你的细胞一些边缘。

或者您可以创建具有边距的自定义单元格。

或者你可以设置你的CollectionviewFlowLayout的属性.sectionInset,这应该是最简单的方法(如果你使用FlowLayout)


Swift 2.0

1
2
self.automaticallyAdjustsScrollViewInsets = false
self.collectionView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)

Swift 4更新(Vinayak Kini答案):

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


在Xcode 8上,如果您正在使用界面构建器,则可以在Size Inspector上设置Section Insets:

enter image description here

enter image description here