aliandmuthu
aliandmuthu

Reputation: 1

How to center a cell in UICollectionView?

I have a UICollectionView which consists of 12 cells from Jan to Dec as shown in the screenshot below:

enter image description here

How can I make the current month to always to be at the center of the collection view? For example, Dec shall be shown on the center for this month.

One of the solutions is to scroll automatically to the next page and center the 12th cell but how can I achieve that?

Upvotes: 0

Views: 266

Answers (2)

Daniel
Daniel

Reputation: 7724

You can use the cellForItem function to define how the cells are going to appear and the UICollectionView function reloadData() to update all the cells always you think it's necessary.

If December should be the cell in the middle, make sure that 5 or 6 cells come before December, you should be able to do this with simple conditions inside cellForItem.

For example, as you have 12 cells, you can get the current month as and integer (12 for December), and you will know that the first month will be 12 - 6 = 6 (June), so you can do this calculation for each indexPath.

To simplify your job:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = ...
    let month = GetCurrentMonthAsInteger()
    var cellMonth = month - 6 + indexPath.row //or section if you have 12 sections
    if(cellMonth < 1) {cellMonth = 12 + cellMonth}
    else if(cellMonth > 12) {cellMonth = cellMonth - 12}
    cell.setInformationForMonth(cellMonth)
    ...
    return cell
}

Upvotes: 1

kanchan verma
kanchan verma

Reputation: 53

You can try making min spacing to zero for cells and lines

Upvotes: 0

Related Questions