Search code examples
iosswiftuicollectionviewreloaddata

Calling the method reloadData()


My app includes two collectionViews , mainCollectionView and nestedCollectionView which is in the mainCollectionViewCell .

It's like the iPhone calendar app , each cell in the mainCollectionView has nestedCollectionView which represents a month(the number of the cells will be the number of the month days).

class cell_Main:UICollectionViewCell{

    let collectionView:UICollectionView = {
        let cv = nestedCollectionView()
        cv.backgroundColor = .white
        return cv
    }()

to update the nestedcollectionView if the month changes , I"ve used nestedcollectionView.reloadData() inside the method(which belongs to mainCollectionView ):

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell_main", for: indexPath) as! cell_Main

        let nested_CollectionView = cell.collectionView as! nestedCollectionView
               .
               .
               .
         nested_CollectionView.reloadData()

}

! if I scroll the mainCollectionView, the nestedCollectionView supposed to be updated (the month will be changed).

my question: the code works fine , but is it the right way to reloadData() here?, does it an expensive CPU work, does the app use too much CPU?


Solution

  • instead of using nested Collection View which represent month in a year , I've tried to make one Main CollectionView , and the number of sections will be 12 (the months number) , each section represent month and in each section the numberOfItemsInSection will be the month days number . and any updation can be here(without using reloadData()):

       func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    }
    

    .finally when we scroll down to the end section we would call reloadData() to update the new numberOfSections and move to the next year .