Margins around cell like in Android GridLayout

陌路散爱 提交于 2019-12-11 16:31:22

问题


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)


来源:https://stackoverflow.com/questions/55659342/margins-around-cell-like-in-android-gridlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!