0

I am a new iOS programming and i am a bit lack at technical skill so, today i have come up with one issue which how to limit number of cell to display on UICollectionView.

For example, i load data from server and it contains 20 of cells. So, when loaded completed the content should be display 10 or less than that because i have another button to display viewAll contents in another collectionView so that it will display all the 20 contents.

How can i acheive something like this?

Visal Sambo
  • 1,270
  • 1
  • 19
  • 33
  • Return whatever number of cells you want to display from `numberOfItemsInSection` method. – Kamran Sep 10 '18 at 09:04
  • Yes. Thank you sir – Visal Sambo Sep 10 '18 at 09:12
  • It is better you use pagination concept of API calling, because the logic you use it's works fine if number of data comes from server is less, but if data is more it is good to use pagination concept. (In that 10 records come from server and when you scroll down to last record you call API again and it give 10 records again if required). search related to pagination concept it helps you more in future. – Hardik Thakkar Sep 10 '18 at 12:44
  • @HardikThakkar thank for your suggestion and i will try to use that component. – Visal Sambo Sep 10 '18 at 14:28

2 Answers2

3

You can try

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return min(10, imagesArr.count) // OR imagesArr.count > 10 ? 10 : imagesArr.count
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

Inside numberOfItemsInSection you could check the data and return the count or your desired max value like this:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return data.count > 10 ? 10 : data.count
}

This is a ternary operator, check this.

aleixrr
  • 461
  • 4
  • 18