Search code examples
swiftcellmargincollectionviewspacing

collection view no margin on right


I have a collection with two column exactly. The image is as given below: enter image description here

The code to make it two column exactly is:

 if let layout = alllistcollview?.collectionViewLayout as? UICollectionViewFlowLayout{
                    layout.minimumLineSpacing = 10
                    layout.minimumInteritemSpacing = 10
                    layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
                    let size = CGSize(width:(alllistcollview!.bounds.width-30)/2, height: 200)
                    layout.itemSize = size
        }

Also,in the storyboard the cell spacing is as follows: enter image description here

The issue is that the right side spacing has not appeared for the second column. Also,some part of the cell seem to be cut off.


Solution

  • First you need to implement UICollectionViewDelegateFlowLayout

    After that add this function like this

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let lay = collectionViewLayout as! UICollectionViewFlowLayout
            let widthPerItem = collectionView.frame.width / 2 - lay.minimumInteritemSpacing
            
            return CGSize(width:widthPerItem, height:150)
        }
    

    I define 150 for height. Don't mind that