在Android中,可以轻松创建具有下一个边距的网格列表:
我找到了适用于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
我该如何解决?
附:我不想对任何东西进行硬编码,因此它适用于所有iPhone / iPad设备
将常量为5的前导,尾随和顶部约束添加到集合视图中。这将解决您的保证金问题
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)