Home > Software design >  Change only the data source in the collectionview?
Change only the data source in the collectionview?

Time:03-11

I have an array of arrays

var firstpage = [ Food(name: "rice", image: "rice"),
               Food(name: "fish", image: "fish"),
               Food(name: "pasta", image: "pasta"),
               Food(name: "burger", image: "burger") ]

var secondpage = [ Food(name: "Apple", image: "Apple"),
                   Food(name: "Orange", image: "Orange")]

var thirdpage =  [
    Food(name: "ice cream", image: "iceCream"),
    Food(name: "Waffel", image: "Waffel")]

lazy var cards = [firstpage, secondpage, thirdpage]

and I display each one in a different view controller with the same code

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
 {
     return firstpage.count
 }
 
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
 {
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! CardCVCell
         cell.foodName.text = self.firstpage[indexPath.row].name
         cell.foodImage.image = UIImage(named: self.firstpage[indexPath.row].image)!
    
         return cell
     }

so I would like to refactor the code and make it more efficient and make one view controller with button so when he click the button only the data source change, first I made an variable called currentShowingCollectionViewIndex which updates when the user click the button to change the index of the array Example : the first time the enter the page currentShowingCollectionViewIndex = 0 so it will show the 'firstpage' when the user click the button again it will update to be 1 and it will show the 'Secondpage'

   @IBAction func pageNextButton(_ sender: UIButton!) {
  
    currentShowingCollectionViewIndex  = 1
    
    if currentShowingCollectionViewIndex == 1 {
       foodArray = cards[1] //foodArray is only an empty array that I cope to it.
    }
    if currentShowingCollectionViewIndex == 2 {
        foodArray = cards[2]
    }
}

but the code is not working and the data is not changing (note: I tried to print the currentShowingCollectionViewIndex value and it is updating) but I don't now why the data is not changing ? please any help

Thank you for your time!

CodePudding user response:

You should reload collectionView after setting new data.

   @IBAction func pageNextButton(_ sender: UIButton!) {
  
    currentShowingCollectionViewIndex  = 1
    
    if currentShowingCollectionViewIndex == 1 {
       foodArray = cards[1] //foodArray is only an empty array that I cope to it.
       self.collectionView.reloadData()
    }
    if currentShowingCollectionViewIndex == 2 {
        foodArray = cards[2]
        self.collectionView.reloadData()
    }
}
  • Related