Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set/Override Padding In UICollectionView Between Cells

I have a UICollectionView and I'm running into an issue with getting the padding between cells. In theory, I should be able to divide the screen by 4, and I can get a cellsize that has 4 images which perfectly take up the screen width. But, it chooses not to do that. Instead it creates 3 images with HUGE padding as shown below:

_cellSize = CGSizeMake(UIScreen.mainScreen().bounds.width/4,UIScreen.mainScreen().bounds.width/4)

enter image description here

So I decreased the cell size a bit to create some padding, and this was closer but I need about half this padding:

_cellSize = CGSizeMake(UIScreen.mainScreen().bounds.width/4.4,UIScreen.mainScreen().bounds.width/4.4)

enter image description here

So I tried making the cells a bit bigger and it rolls over to the next row and puts 3 items with HUGE padding again.

_cellSize = CGSizeMake(UIScreen.mainScreen().bounds.width/4.3,UIScreen.mainScreen().bounds.width/4.3)

enter image description here

Can I specify the padding between cells without it deciding that if the padding is below "x" amount that it creates a new row instead? Like can I set the threshold padding before a new row to say, 0?

I want to make it this thin: enter image description here

like image 846
Aggressor Avatar asked May 27 '26 13:05

Aggressor


1 Answers

You only need to do the correct calculation that includes the spaces you want to the edges as well as the space between the cells. For instance, if you want 3 cells across with 5 points to the edges and between the cells, you should have something like this,

override func viewDidLoad() {
        super.viewDidLoad()
        var layout = self.collectionView.collectionViewLayout as UICollectionViewFlowLayout
        layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
        layout.minimumInteritemSpacing = 5; // this number could be anything <=5. Need it here because the default is 10.
        layout.itemSize = CGSizeMake((self.collectionView.frame.size.width - 20)/3, 100) // 20 is 2*5 for the 2 edges plus 2*5 for the spaces between the cells
    }
like image 190
rdelmar Avatar answered May 30 '26 11:05

rdelmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!