Midhun MP
Midhun MP

Reputation: 107131

Collection view spacing breaks the ui

I'm trying to create an UI like below.

3 Column Layout

For this purpose I'm using UICollectionView and FlowLayout.

For showing the first cell with full width and remaining cell as 3 column, I've implemented the sizeForItemAtIndexPath: and minimumInteritemSpacingForSectionAtIndex methods:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
    var cellSize = CGSizeZero

    if indexPath.item == 0
    {
        let width  = self.cvMedia.frame.width - 20
        let height = (width * 9)/16
        cellSize   = CGSize(width: width, height: height)
    }
    else
    {
        let width  = self.cvMedia.frame.width / 3 - 20
        let height = (width * 16)/9
        cellSize   = CGSize(width: width, height: height)
    }

    return cellSize
}



func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat
{
    return 20.0
}

But I'm getting the following output in iPhone 6SPlus and iPhone 6Plus:

Actual Outcome

I tried by changing the item spacing from 20 to 19 and it worked on simulator, but on actual device it still shows the same behaviour. If I change the spacing values I'm getting the correct output on some device versions, and not working on some versions. I can add a device version check and based on that I can return the value. But it is not an elegant solution and it will break on future versions. Can anyone help me to solve this issue ? Thanks in advance.

Upvotes: 1

Views: 208

Answers (2)

Ariel
Ariel

Reputation: 2742

You should use the collection view's width as your parameter when making this layout.

For instance,

  1. You need 3 cells to fit the view.
  2. The cells must have 20pt spacing in between them.

Solution:

Calculate the size of the cell at runtime either on viewWillAppear() or cellForRowAtIndexPath()

Scenario:

Width of device is 320pt. Collectionview's width is 300pt( spacing 10pt L & R) Spacing : 20pt between cells. Cell's needed 3!! Cell Size: ?

Now..Start calculating in either method.

Cell Spacing = (3-1) * 20 = 2 * 20 = 40pt

Remaining collection view width = 300pt - 40pt = 260pt

Cell size = 260pt/3 = 86.667 pt. (86pt apprx).

In Code:

cellWidth = ( collectionView?.bounds.width - minimumSpacing * (numberOfCellsInARow - 1 ) ) / numberOfCellsInARow

Also, this only gives the cellWidth. You need cellHeight as well. You might already have an aspect ratio for the cell. Using that, calculate the cellHeight as well.

Kind Regards,
Suman Adhikari

Upvotes: 1

Happiehappie
Happiehappie

Reputation: 1074

Check out this image and change the values for min spacing to 0 for both cells and lines

Upvotes: 0

Related Questions