Asis
Asis

Reputation: 733

Custom Layout on CollectionView

I have a cell which width depends on the content. Now the content are show respectively as in the picture. There is a big gap in the middle which is kind of ugly.

Current View in CollectionView

The end result I was hopping is some thing like in the next picture. I want space between the cell to remain constant even if there is some huge gap in the end of that particular row.

enter image description here

Upvotes: 0

Views: 834

Answers (1)

Abid Bhatti
Abid Bhatti

Reputation: 101

You can use custom layout for your collection to align your cells in collection view.

class CustomCollectionViewLayout: UICollectionViewFlowLayout {

// function which will return attributes for elements...
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    
    // for section insets and item spacing...
    sectionInset = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
    minimumLineSpacing = 15
    
    // get original attributes of elements in collection view for further modification (in this case to align collection view cells to left side)...
    guard let originalAttributes = super.layoutAttributesForElements(in: rect) else {
        return nil
    }
    
    // margin for cells for spacing...
    var leftMargin: CGFloat = sectionInset.left
    
    // maxY property which helps in resetting leftMargin when cells switch to next line...
    var maxY: CGFloat = -1.0
    
    // modifying original attributes to align them on left side...
    let attributes = originalAttributes.map { (attribute) -> UICollectionViewLayoutAttributes in
        
        // reset leftMargin and maxY when cell will switch to next line...
        if attribute.frame.maxY > maxY {
            leftMargin = sectionInset.left
            maxY = attribute.frame.maxY
        }
        
        // setting oring x for current attribute...
        attribute.frame.origin.x = leftMargin
        
        // appending width of attribute + line spacing to calculate origin x for next attribute
        leftMargin += attribute.frame.width + minimumLineSpacing
        
        // return attribute for current element
        return attribute
    }
    
    // return attributes for all elements in collection view
    return attributes
    
}

}

and then simply in your view controller you can set this custom layout for your collection view like this :

let layout = CustomCollectionViewLayout()
collectionView.collectionViewLayout = layout

Upvotes: 3

Related Questions