UIcollectionView with array no loading sections

Hi, im struggle with my cell model it's only showing my array position 0
what i'm trying to reach is show in each UICollectionView the information inside
arregloBidimencional
which contains let episodes: [episodess]? and let tack: Int?
episodess is my main struct for the didSet inside each UICollectionviewCell
and tack is my identifier for each array of [episodess]
Code Block
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == UI.castCollectionView{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifierSeasons", for: indexPath) as! SeasonCell
cell.backgroundColor = .clear
let arreglo = arraySeasonsEpisodes[indexPath.item]
cell.model = arreglo
return cell
}

var arraySeasonsEpisodes: [episodess] = [] its type of episodess

so my model to get the previous data is
Code Block
struct episodess: Initiable {
let episode_number: Int?
let name: String?
let still_path: String?
init() {
self.episode_number = 0
self.name = ""
self.still_path = ""
}
init(dictionary: NSDictionary) {
self.episode_number = dictionary["episode_number"] as? Int ?? 0
self.name = dictionary["name"] as? String ?? ""
self.still_path = dictionary["still_path"] as? String ?? ""
}
}
struct arregloBidimencional: Initiable {
let episodes: [episodess]?
let tack: Int?
init() {
self.episodes = [episodess]()
self.tack = 0
}
init(arreglo: [episodess], tag: Int) {
self.episodes = arreglo
self.tack = tag
}
}

so the didset in UICollectionViewCell it's set like this
Code Block
class SeasonCell: UICollectionViewCell {
var model: episodess? {
didSet {
guard let viewModel = model else { return }
let episodio = viewModel.episode_number
let nombre = viewModel.name
let guardado = viewModel.still_path
episodeNumber.text = "Episode Number: \(episodio ?? 0)"
episodeName.text = "Episode Name: \(nombre ?? "")"
let image = "https://image.tmdb.org/t/p/w500\(guardado ?? "")"
if image == "" || image == "undefined" {
seasonImage.image = UIImage(named: "")
seasonImage.contentMode = .scaleAspectFill
}else{
seasonImage.downloaded(from: image)
seasonImage.contentMode = .scaleAspectFill
}
}
}


this is how i storage the data from the json dictionary
Code Block
let toneCategories = jsonDictionary["episodes"] as? [NSDictionary] ?? []
for category in toneCategories {
let show = episodess(dictionary: category)
arraySeasonsEpisodes.append(show)
let number = Int(season_number) ?? 0
let reversedCollection = (1 ... number)
//for index in reversedCollection {
for (index, element) in reversedCollection.enumerated() {
print(index, ":", element)
let fixed = index - 1
if fixed <= 0 {
let arreglo = arregloBidimencional(arreglo: [show], tag: 0)
arregloDeArreglos.append([arreglo])
}else if fixed >= 1{
let fixed2 = index
let arreglo = arregloBidimencional(arreglo: [show], tag: fixed2)
arregloDeArreglos.append([arreglo])
}
}
}

Accepted Reply

If the collectionViews are inside tableView cells, when you dequeue a cell, you need to define the content of the cell in the cellAtRow func. Otherwise, you get reusing queued cells, with any content that is left there.
The content should be the corresponding collectionView.

Replies

it's only showing my array position 0 
Do you mean it shows only one cell or the same cell 0 content in all cells ?

Have you defined numberOfCells ?
Code Block
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arraySeasonsEpisodes.count
}


Do you mean it shows only one cell or the same cell 0 content in all cells ?


the same cell 0 content in all cells


Have you defined numberOfCells ?

yes
Could you
Code Block
print(arraySeasonsEpisodes)

To see if all items are the same.

as you can see the items are not the same

Code Block
[MovieDataBase.episodess(episode_number: Optional(1), name: Optional("121045"), still_path: Optional("/b9hFk5kwRcFUorxLQsOHasJnbDH.jpg")), MovieDataBase.episodess(episode_number: Optional(2), name: Optional("131045"), still_path: Optional("/mSZDdQLHnDousFg35ndlmv42908.jpg")), MovieDataBase.episodess(episode_number: Optional(3), name: Optional("181045"), still_path: Optional("/57bidANnv5zdPmJckmPL9f4Ogb7.jpg")), MovieDataBase.episodess(episode_number: Optional(4), name: Optional("291045"), still_path: Optional("/swmIOzEJ8uIjCdd5B4w9Ln5qXsJ.jpg")), MovieDataBase.episodess(episode_number: Optional(5), name: Optional("301045"), still_path: Optional("/2x9v9YupwZnMBnvCUOwaOv8UEQV.jpg")), MovieDataBase.episodess(episode_number: Optional(6), name: Optional("311045"), still_path: Optional("/uFY25TSNrOxbL18jDV1pSjWPKEK.jpg")), MovieDataBase.episodess(episode_number: Optional(7), name: Optional("011145"), still_path: Optional("/8LGArTKq5oMnKR9AjdRd3ocxJWu.jpg")), MovieDataBase.episodess(episode_number: Optional(8), name: Optional("021145"), still_path: Optional("/yEBAannVEt2QhyUKyjlXhXrEVld.jpg")), MovieDataBase.episodess(episode_number: Optional(9), name: Optional("031145"), still_path: Optional("/nf1zvR7D4kN1Xa1wlxXeuUrWpOo.jpg")), MovieDataBase.episodess(episode_number: Optional(10), name: Optional("130146"), still_path: Optional("/1lTlSWY4chqpv1ibeQz4eYHaePf.jpg")), MovieDataBase.episodess(episode_number: Optional(11), name: Optional("140146"), still_path: Optional("/qTKxjZTbiCqZ6lywwfmfTLX8QnK.jpg")), MovieDataBase.episodess(episode_number: Optional(12), name: Optional("150146"), still_path: Optional("/8duv3ltJa7Olb721zsqcbss0kVx.jpg")), MovieDataBase.episodess(episode_number: Optional(1), name: Optional("Episode 1"), still_path: Optional("/24VlK7Ed5VFa0yE2kEmDPzyYks.jpg")), MovieDataBase.episodess(episode_number: Optional(2), name: Optional("Episode 2"), still_path: Optional("/eoyTsCYEAymTAhBgXIbIfW2jrwz.jpg")), MovieDataBase.episodess(episode_number: Optional(3), name: Optional("Episode 3"), still_path: Optional("/1EgiONNX9CgO6i4DjyeVBvsvT9v.jpg")), MovieDataBase.episodess(episode_number: Optional(4), name: Optional("Episode 4"), still_path: Optional("/4lZnqwPkNmnVEZ6ipID92BiWDkd.jpg")), MovieDataBase.episodess(episode_number: Optional(5), name: Optional("Episode 5"), still_path: Optional("/4wkH3s9d7YFvnjvQ24rS1pj4oUk.jpg")), MovieDataBase.episodess(episode_number: Optional(6), name: Optional("Episode 6"), still_path: Optional("/46XRAOhySNHl1O0qTHMUdUxfDcA.jpg")), MovieDataBase.episodess(episode_number: Optional(7), name: Optional("Episode 7"), still_path: Optional("/lbVYNXOtQSVU69ee7qbHWJ1f7b8.jpg")), MovieDataBase.episodess(episode_number: Optional(8), name: Optional("Episode 8"), still_path: Optional("/95UudD6foD0V7xJc345sJSZ9vUW.jpg")), MovieDataBase.episodess(episode_number: Optional(9), name: Optional("Episode 9"), still_path: Optional("")), MovieDataBase.episodess(episode_number: Optional(10), name: Optional("Episode 10"), still_path: Optional("")), MovieDataBase.episodess(episode_number: Optional(11), name: Optional("Episode 11"), still_path: Optional(""))]

So, next test I would do is the didSet, to check:
  • if it is properly called

  • if the content of model is correct

Could you add 2 print statements:
Code Block
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == UI.castCollectionView{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifierSeasons", for: indexPath) as! SeasonCell
cell.backgroundColor = .clear
let arreglo = arraySeasonsEpisodes[indexPath.item]
cell.model = arreglo
print(indexPath.item, arreglo.episode_number)
return cell
}

and
Code Block
class SeasonCell: UICollectionViewCell {
var model: episodess? {
didSet {
guard let viewModel = model else { return }
let episodio = viewModel.episode_number
let nombre = viewModel.name
let guardado = viewModel.still_path
episodeNumber.text = "Episode Number: \(episodio ?? 0)"
episodeName.text = "Episode Name: \(nombre ?? "")"
let image = "https :// image.tmdb.org/t/p/w500\(guardado ?? "")"
if image == "" || image == "undefined" {
seasonImage.image = UIImage(named: "")
seasonImage.contentMode = .scaleAspectFill
} else {
seasonImage.downloaded(from: image)
seasonImage.contentMode = .scaleAspectFill
}
print("model", model.episode_number) // <<<----
}
}


Note: struct names should start with Uppercase.
What is Initiable ?
Why do you need this if-statement?
Code Block
if collectionView == UI.castCollectionView{

Are you still trying to show UICollectionView inside each UITableViewCell as shown in another thread of yours?

I guess you are not managing such nested structure well.

Please show your latest definition of NumberOfSeasonsCell if you are still using it.
Also all the code related to UI.castCollectionView is needed.
One more, please show all the code of collectionView(_:cellForItemAt:). It is very likely there is something wrong in the hidden parts of your code.

Print statements inside CellForItemAt and UICollectionViewCell



model Optional(4)

3 Optional(4)

model Optional(5)

4 Optional(5)

model Optional(6)

5 Optional(6)

model Optional(7)

6 Optional(7)

model Optional(8)

7 Optional(8)

model Optional(9)

8 Optional(9)

model Optional(10)

9 Optional(10)

model Optional(11)

10 Optional(11)

model Optional(12)

11 Optional(12)

model Optional(1)

12 Optional(1)

model Optional(2)

13 Optional(2)

model Optional(3)

14 Optional(3)

model Optional(4)

15 Optional(4)

model Optional(5)

16 Optional(5)

model Optional(6)

17 Optional(6)

model Optional(7)

18 Optional(7)

model Optional(8)

19 Optional(8)

model Optional(9)

20 Optional(9)

model Optional(10)

21 Optional(10)

model Optional(11)

22 Optional(11)

Why do you need this if-statement?

because i have 2 CollectionsView in the same View


Are you still trying to show UICollectionView inside each UITableViewCell as shown in another thread of yours?

It shows already and can be scrolled horizontally, i solve my problem now the thing is it shows the same cell 0 content in all cells


Please show your latest definition of NumberOfSeasonsCell if you are still using it.

here's the code i'm not using this any more because it detects how may arrows will be display for current show and can be scrolled

Code Block class NumberOfSeasonsCell: UITableViewCell, ViewDelegate {
    var compactConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
    var regularConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
    var largeConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
    lazy var seasonsCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 30
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.clear
        cv.register(SeasonCell.self, forCellWithReuseIdentifier: "identifierSeasons")
        cv.showsHorizontalScrollIndicator = false
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()
  override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initComponents()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {
        seasonsCollectionView.delegate = dataSourceDelegate
        seasonsCollectionView.dataSource = dataSourceDelegate
        seasonsCollectionView.tag = row
        seasonsCollectionView.setContentOffset(seasonsCollectionView.contentOffset, animated:false) // Stops collection view if it was scrolling.
        seasonsCollectionView.reloadData()
    }
var collectionViewOffset: CGFloat {
        set { seasonsCollectionView.contentOffset.x = newValue }
        get { return seasonsCollectionView.contentOffset.x }
    }
    func initComponents() {
        addComponents()
        setAutolayout()
        activateCurrentLayout()
    }
    func addComponents() {
        self.addSubview(seasonsCollectionView)
    }
    func setAutolayout() {
        largeConstraints = [
            seasonsCollectionView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
            seasonsCollectionView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            seasonsCollectionView.widthAnchor.constraint(equalTo: self.widthAnchor),
            seasonsCollectionView.heightAnchor.constraint(equalTo: self.heightAnchor),
        ]
    }
  func activateCurrentLayout() {
        NSLayoutConstraint.activate(largeConstraints)
    }
}
extension UITableViewCell {
    open override func addSubview(_ view: UIView) {
        super.addSubview(view)
        sendSubviewToBack(contentView)
    }
}



Also all the code related to UI.castCollectionView is needed.

UI.castCollectionView is not part of the problem because its an independent UICollectionView working fine the problem is with cell and cell model of the other UICollectionView inside the else cellForItemAt

let arreglo = arraySeasonsEpisodes[indexPath.item]

            cell.model = arreglo


Code Block
lazy var castCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 20
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.clear
        cv.register(CastCell.self, forCellWithReuseIdentifier: "identifierCast")
        cv.isPagingEnabled = true
     cv.showsVerticalScrollIndicator = false
     cv.showsHorizontalScrollIndicator = false
     cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()


Code Block
extension SelectedShowVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == UI.castCollectionView{
            return arrayCast.count
        }else{
            return arraySeasonsEpisodes.count
            //return model[collectionView.tag].count
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if collectionView == UI.castCollectionView{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifierCast", for: indexPath) as! CastCell
        
            
            cell.backgroundColor = .clear
            cell.model = arrayCast[indexPath.item]
            
            return cell
        }else{
            
            
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifierSeasons", for: indexPath) as! SeasonCell
            cell.backgroundColor = .clear
            let arreglo = arraySeasonsEpisodes[indexPath.item]
            cell.model = arreglo
            
            
            print(indexPath.item, arreglo.episode_number)
           
            return cell
        }
        
    
}




Print statements inside CellForItemAt and UICollectionViewCell

model Optional(4)
3 Optional(4)

I am surprised it does not start at 0
model Optional(1)
0 Optional(1)

I'm sorry i didn't copy the entire print

model Optional(1)

0 Optional(1)
model Optional(2)
1 Optional(2)
model Optional(3)
2 Optional(3)
model Optional(4)
3 Optional(4)
model Optional(5)
4 Optional(5)
model Optional(6)
5 Optional(6)
model Optional(7)
6 Optional(7)
model Optional(8)
7 Optional(8)
model Optional(9)
8 Optional(9)
model Optional(10)
9 Optional(10)
model Optional(11)
10 Optional(11)
model Optional(12)
11 Optional(12)
model Optional(1)
12 Optional(1)
model Optional(2)
13 Optional(2)
model Optional(3)
14 Optional(3)
model Optional(4)
15 Optional(4)
model Optional(5)
16 Optional(5)
model Optional(6)
17 Optional(6)
model Optional(7)
18 Optional(7)
model Optional(8)
19 Optional(8)
model Optional(9)
20 Optional(9)
model Optional(10)
21 Optional(10)
model Optional(11)
22 Optional(11)
model Optional(9)
20 Optional(9)


this is how i storage the information from the JSON response

Code Block
let toneCategories = jsonDictionary["episodes"] as? [NSDictionary] ?? []
                       for category in toneCategories {
                        let show = episodess(dictionary: category)
                        arraySeasonsEpisodes.append(show)
                        let number = Int(season_number) ?? 0
                        let reversedCollection = (1 ... number)
                        for (index, element) in reversedCollection.enumerated() {
                            let fixed = index - 1
                            if fixed <= 0 {
                                let arreglo = arregloBidimencional(arreglo: [show], tag: 0)
                                arregloDeArreglos.append([arreglo])
                            }else if fixed >= 1{
                                let fixed2 = index
                                let arreglo = arregloBidimencional(arreglo: [show], tag: fixed2)
                                arregloDeArreglos.append([arreglo])
                            }
                        }
                       }


the struct for arregloBidimencional

Code Block
var arregloDeArreglos: [[arregloBidimencional]] = []


Code Block
struct arregloBidimencional: Initiable {
    let episodes: [episodess]?
    let tack: Int?
    
    init() {
        
        self.episodes = [episodess]()
        self.tack = 0
        
        }
    
    init(arreglo: [episodess], tag: Int) {
        self.episodes = arreglo
        self.tack = tag
    }
}

Could you show how episodeNumber and episodeName IBOutlets are defined ?

Is there a xib associated with the cell ?
this is the entire code of the cell

Code Block
import UIKit
class SeasonCell: UICollectionViewCell {
    
    var model: episodess? {
        didSet {
            guard let viewModel = model else { return }
            let episodio = viewModel.episode_number
            let nombre = viewModel.name
            let guardado = viewModel.still_path
            episodeNumber.text = "Episode Number: \(episodio ?? 0)"
            episodeName.text = "Episode Name: \(nombre ?? "")"
            let image = "w500\(guardado ?? "")"
            if image == "" || image == "undefined" {
                seasonImage.image = UIImage()
                seasonImage.contentMode = .scaleAspectFill
            }else{
                seasonImage.downloaded(from: image)
                seasonImage.contentMode = .scaleAspectFill
            }
            print("model", viewModel.episode_number) // <<<----
        }
    }
    override func prepareForReuse() {
        super.prepareForReuse()
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    let seasonImage: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleToFill
        iv.backgroundColor = .clear
        iv.image = UIImage(named: "")
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()
    
    var episodeNumber: UILabel = {
        let label = UILabel()
        label.text = ""
        label.numberOfLines = 1
        label.textAlignment = .left
        label.font = Fonts.AVENIR.of(size: 10)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.white
        return label
    
        }()
    
    var episodeName: UILabel = {
        let label = UILabel()
        label.text = ""
        label.numberOfLines = 1
        label.textAlignment = .left
        label.font = Fonts.AVENIR.of(size: 10)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.white
        return label
    
        }()
    
    func setupViews() {
        addSubview(seasonImage)
        addSubview(episodeNumber)
        addSubview(episodeName)
        
        
        NSLayoutConstraint.activate([
            seasonImage.centerYAnchor.constraint(equalTo: self.centerYAnchor),
            seasonImage.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            seasonImage.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1),
            seasonImage.heightAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6),
            
            
            episodeNumber.leftAnchor.constraint(equalTo: seasonImage.leftAnchor),
            episodeNumber.topAnchor.constraint(equalTo: seasonImage.bottomAnchor, constant: 8),
            episodeNumber.rightAnchor.constraint(equalTo: seasonImage.rightAnchor),
            episodeName.leftAnchor.constraint(equalTo: episodeNumber.leftAnchor),
            episodeName.rightAnchor.constraint(equalTo: seasonImage.rightAnchor),
            episodeName.topAnchor.constraint(equalTo: episodeNumber.bottomAnchor, constant: 8),
      
        ])
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

Would need to test with complete code, to confirm.
If you want to post an email for a short moment.

But I would do
Code Block
setupViews()

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

With present code, I suspect you do not set the labels of the cell you dequeue…
i tried like this but same problem



Code Block
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifierSeasons", for: indexPath) as! SeasonCell
            cell.backgroundColor = .clear
            let arreglo = arraySeasonsEpisodes[indexPath.item]
            cell.model = arreglo
            cell.setupViews()
            
            print(indexPath.item, arreglo.episode_number)
           
            return cell

it shows the same cell 0 content in all cells

In your view controller, you have two types of cells, do you mean the same cell 0 as UITableViewCell or UICollectionViewCell?
How many UICollectionView exist in your view controller?

here's the code i'm not using

Thanks, but no need to show unused code.

UI.castCollectionView is not part of the problem

Why can you believe so? If all was working as expected, you would never experience this sort of weird problem.

the problem is with cell and cell model of the other UICollectionView inside the else cellForItemAt

I do not understand why you restrict where to check. Do you really want to solve your issue?