Margins around cell like in Android GridLayout

2019-08-20 02:30发布

问题:

In Android it's easy to create a grid list with the next margins:

I found this solution for iOS but it doesn't add margins between cell and parent view, only between cells

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

How can I solve it?

P.S. I don't want to hardcode anything, so it should work ok for all iPhone/iPad devices

回答1:

Add leading,trailing and top constraint with constant of 5 to your collection view.This will resolve your margin issue



回答2:

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)