0

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?

Vivek Molkar
  • 3,744
  • 1
  • 31
  • 43
  • Possible duplicate of [How to center align the cells of a UICollectionView?](https://stackoverflow.com/questions/13588283/how-to-center-align-the-cells-of-a-uicollectionview) – Kasnady Dec 06 '17 at 04:56
  • Use colletion view's selectItem delegate method. – El Tomato Dec 06 '17 at 05:02
  • Please check [How to center a UICollectionView when it is tapped?](https://stackoverflow.com/questions/17879533/how-to-center-a-uicollectionview-when-it-is-tapped) may be it helps you. – Mehul Sojitra Dec 06 '17 at 06:43

2 Answers2

1

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
}
Daniel
  • 5,752
  • 4
  • 21
  • 48
0

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