I made a collection layout.
To make the separator visible, Set the background color of the collection view to gray. One row per section.
Useage:
let layout = GridCollectionViewLayout()
layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
layout.cellWidth = 50 // if not set, cellWidth = Collection.width/numberOfItems(inSection)
collectionView.collectionViewLayout = layout
Layout:
import UIKit
class GridCollectionViewLayout: UICollectionViewLayout {
var cellWidth : CGFloat = 0
var cellHeight : CGFloat = 0
var seperator: CGFloat = 1
private var cache = [UICollectionViewLayoutAttributes]()
override func prepare() {
guard let collectionView = self.collectionView else {
return
}
self.cache.removeAll()
let numberOfSections = collectionView.numberOfSections
if cellHeight <= 0
{
cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
}
for section in 0..<collectionView.numberOfSections {
let numberOfItems = collectionView.numberOfItems(inSection: section)
let cellWidth2 : CGFloat
if cellWidth <= 0
{
cellWidth2 = (collectionView.bounds.width - seperator*CGFloat(numberOfItems-1))/CGFloat(numberOfItems)
}
else
{
cellWidth2 = cellWidth
}
for row in 0..<numberOfItems {
let indexPath = NSIndexPath(row: row, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
attributes.frame = CGRect(x: (cellWidth2+seperator)*CGFloat(row),
y: (cellHeight+seperator)*CGFloat(section),
width: cellWidth2,
height: cellHeight)
//row_temp.append(attributes)
self.cache.append(attributes)
}
//self.itemAttributes.append(row_temp)
}
}
override var collectionViewContentSize: CGSize {
guard let collectionView = collectionView else
{
return CGSize.zero
}
if (collectionView.numberOfSections <= 0)
{
return collectionView.bounds.size
}
let width:CGFloat
if cellWidth <= 0
{
width = collectionView.bounds.width
}
else
{
width = cellWidth*CGFloat(collectionView.numberOfItems(inSection: 0))
}
let numberOfSections = CGFloat(collectionView.numberOfSections)
var height:CGFloat = 0
height += numberOfSections * cellHeight
height += (numberOfSections - 1) * seperator
return CGSize(width: width, height: height)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
}