像Android GridLayout中的单元格周围的边距

时间:2019-04-12 20:59:38

标签: ios uicollectionview uicollectionviewcell uicollectionviewflowlayout

在Android中,使用下一个边距创建网格列表很容易:

enter image description here

我找到了适用于iOS的解决方案,但它并未在单元格和父视图之间添加边距,仅在单元格之间添加了边距

let itemSpacing: CGFloat = 3
let itemsInOneLine: CGFloat = 2
flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1) //collectionView.frame.width is the same as  UIScreen.main.bounds.size.width here.
flow.itemSize = CGSize(width: floor(width/itemsInOneLine), height: width/itemsInOneLine)
flow.minimumInteritemSpacing = 3
flow.minimumLineSpacing = 3

enter image description here

我该如何解决?

P.S。我不想对任何内容进行硬编码,因此对所有iPhone / iPad设备都可以正常工作

2 个答案:

答案 0 :(得分:1)

在收款视图中添加常量为5的前导,尾随和最高约束。这将解决您的保证金问题

答案 1 :(得分:1)

let itemSpacing: CGFloat = 3
let itemsInOneLine: CGFloat = 2
let flow = UICollectionView().collectionViewLayout as! UICollectionViewFlowLayout
flow.sectionInset = UIEdgeInsets(top: itemSpacing, left: itemSpacing, bottom: itemSpacing, right: itemSpacing)
flow.minimumInteritemSpacing = itemSpacing
flow.minimumLineSpacing = itemSpacing
let cellWidth = (UIScreen.main.bounds.width - (itemSpacing * 2) - ((itemsInOneLine - 1) * itemSpacing)) / itemsInOneLine
flow.itemSize = CGSize(width: cellWidth, height: cellWidth)