Margins around cell like in Android GridLayout

2019-08-20 02:22发布

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

enter image description here

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

enter image description here

How can I solve it?

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

2条回答
神经病院院长
2楼-- · 2019-08-20 02:50
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)
查看更多
ら.Afraid
3楼-- · 2019-08-20 03:15

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

查看更多
登录 后发表回答