Home > OS >  index out of range double array collection view
index out of range double array collection view

Time:09-05

I fill cellTypes array

func fillCellTypes() {
    cellTypes = []
    cellTypes.append(Array(repeating: CellType.vanc, count: self.vancPhotos.count))
    cellTypes.append(Array(repeating: CellType.calg, count: self.calgPhotos.count))
    cellTypes.append(Array(repeating: CellType.mon, count: self.monPhotos.count))
    cellTypes.append(Array(repeating: CellType.ott, count: self.ottPhotos.count))
    cellTypes.append(Array(repeating: CellType.tor, count: self.torPhotos.count))
    self.collectionView.reloadData()
    print(cellTypes)
}

My CellType enum

enum CellType {
    case vanc
    case calg
    case ott
    case tor
    case mon
}

var cellTypes: [[CellType]] = []

in config I fill all photos arrays

var vancPhotos: [PhotoModel] = []
var calgPhotos: [PhotoModel] = []
var ottPhotos: [PhotoModel] = []
var torPhotos: [PhotoModel] = []
var monPhotos: [PhotoModel] = []
var photos: [PhotoModel] = []

func configCollectionView() {
        photoViewModel.getPhotos()
        photos = photoViewModel.photos
        vancPhotos = photoViewModel.vancPhotos
        calgPhotos = photoViewModel.calgPhotos
        ottPhotos =  photoViewModel.ottPhotos
        torPhotos =  photoViewModel.torPhotos
        monPhotos =  photoViewModel.monPhotos

Inside cellForItemAt I get index out of range at switch.

extension WeatherDetailVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellTypes.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch cellTypes[indexPath.section][indexPath.row] {
        case .tor: return configureTorontoCell(indexPath: indexPath)
        ...
        }
    }
    
    func configureTorontoCell(indexPath: IndexPath) -> PhotoCollectionViewCell  {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoCollectionViewCell.identifier, for: indexPath) as? PhotoCollectionViewCell
        cell?.setup(photoViewModel.torPhotos[indexPath.row])
        return cell!
    }

return cellTypes.count is 3 so my arrays are filled but cellforitem is some how wrong.

CodePudding user response:

You would need to implement this differently you need multiple sections as your data consists of an array of arrays:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    cellTypes[section].count
}

and add this function:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    cellTypes.count
}
  • Related