John C
John C

Reputation: 517

CollectionView not displaying the correct data in the cells

When I scroll through the collectionView, the data displayed is incorrect and also changes when scrolling up and down. I have implemented the function prepareForReuse in the collection view cell

The data in my arrays are correct, and the data inside

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)

is correct as well when I log it.

Collection View Cell

class ToonCollectionCell: UICollectionViewCell {
    @IBOutlet weak var toonTitle: UILabel!
    @IBOutlet weak var toonImage: UIButton!
    
    override func prepareForReuse() {
        super.prepareForReuse()
        toonTitle.text = nil
        toonImage.imageView!.image = nil
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
}

Table View Cell

import UIKit
import SDWebImage

class ToonCell: UITableViewCell {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var date: UILabel!

    @objc func reloadTableViewData() {
        collectionView.reloadData()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.showsHorizontalScrollIndicator = false
        
        NotificationCenter.default.addObserver(self, selector: #selector(reloadTableViewData), name: NSNotification.Name(rawValue: "reloadData"), object: nil)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

extension HomePage: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dateArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "toonTitle") as? toonTitle else {
            fatalError("Cannot create cell")
        }
        
        cell.date.text = dateArr[indexPath.row]
     
        if(dateArr[indexPath.row] == "Monday") {
           // cell.identi = "123"
            cell.collectionView.tag = 11
        }
        else if(dateArr[indexPath.row] == "Tuesday") {
            cell.collectionView.tag = 22
        }
        
        else if(dateArr[indexPath.row] == "Wednesday") {
            cell.collectionView.tag = 33
        }
        
        else if(dateArr[indexPath.row] == "Thursday") {
            cell.collectionView.tag = 44
        }
        
        else if(dateArr[indexPath.row] == "Friday") {
            cell.collectionView.tag = 55
        }
        
        else if(dateArr[indexPath.row] == "Saturday") {
            cell.collectionView.tag = 66
        }
        
        else if(dateArr[indexPath.row] == "Sunday") {
            cell.collectionView.tag = 77
        }
        else {
            cell.collectionView.tag = 1
        }
      
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 300
    }
    
}

extension ToonCell: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
      //  print("Tag: ", collectionView)
        if(subscribedToons.isEmpty) {
            return 0
        }

        if(collectionView.tag == 11) {
           // print("Monday: ",subscribedToons["Monday"]!.count)
            return subscribedToons["Monday"]!.count
        }
        else if(collectionView.tag == 22) {
           // print("Tues: ",subscribedToons["Tuesday"]!.count)
            return subscribedToons["Tuesday"]!.count
        }
        else if(collectionView.tag == 33) {
            //print("Wed: ",subscribedToons["Wednesday"]!.count)
            return subscribedToons["Wednesday"]!.count
        }
        else if(collectionView.tag == 44) {
           // print("Thurs: ",subscribedToons["Thursday"]!.count)
            return subscribedToons["Thursday"]!.count
        }
        else if(collectionView.tag == 55) {
           // print("Fri: ",subscribedToons["Friday"]!.count)
            return subscribedToons["Friday"]!.count
        }
        else if(collectionView.tag == 66){
            //print("Sat: ",subscribedToons["Saturday"]!.count)
            return subscribedToons["Saturday"]!.count
        }
        else if(collectionView.tag == 77){
           // print("TEST COUNT: ",subscribedToons["Sunday"]!.count)
            //print("Sun: ",subscribedToons["Sunday"]!.count)
            return subscribedToons["Sunday"]!.count
        }
        
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ToonCollectionCell
        let collectionIndex = collectionView.tag
        
        var day = ""
        
        if(collectionView.tag == 11) {
            day = "Monday"
        }
        else if(collectionView.tag == 22) {
           day = "Tuesday"
        }
        else if(collectionView.tag == 33) {
           day = "Wednesday"
        }
        else if(collectionView.tag == 44) {
            day = "Thursday"
        }
        else if(collectionView.tag == 55) {
            day = "Friday"
        }
        else if(collectionView.tag == 66) {
            day = "Saturday"
            
        }
        else if(collectionView.tag == 77) {
            day = "Sunday"
        }
        
        if(subscribedToons[day]!.count == 0) {
            print("COUNT IS 0")
        }
        
        cell.toonImage?.layoutIfNeeded()
        cell.toonImage?.subviews.first?.contentMode = .scaleAspectFill
        
        cell.toonTitle.text = subscribedToons[day]![indexPath.row]["title"] as! String
        var toonId = subscribedToons[day]![indexPath.row]["toonId"] as! String
            
        var url = "urlexample" + toonId + "?alt=media&token="
        cell.toonImage?.sd_setBackgroundImage(with: URL(string: url)!, for: .normal)
        cell.layoutIfNeeded()
        
        return cell
        
        
    }
    
}

HomePage View Controller

class HomePage: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var exitSearch: UIButton!
    @IBOutlet weak var searchBar: UITextField!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.searchBar.delegate = self
        self.tableView.delegate = self
        self.tableView.dataSource = self
        tableView.separatorColor = .clear
        searchBar.addPadding(.left(20))
        searchBar.addPadding(.right(40))
        exitSearch.isHidden = true
        let currentDate = Date()
        var dateComponent = DateComponents()
        
        for i in 0...6 { // Appends the following days to dateArr
            dateComponent.day = i
            let futureDate = Calendar.current.date(byAdding: dateComponent, to: currentDate)
            let index = Calendar.current.component(.weekday, from: futureDate!)
            let appendWeekday = Calendar.current.weekdaySymbols[index-1]
            dateArr.append(appendWeekday)
        }
        print(dateArr)
    }

    @IBAction func exitButtonPressed(_ sender: UIButton) {
        exitSearch.isHidden = true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        exitSearch.isHidden = false
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        exitSearch.isHidden = true
    }
    
   

}

Upvotes: 1

Views: 715

Answers (1)

John C
John C

Reputation: 517

I figured out the answer:

I had to add these lines of code into my ToonCell file

@objc func reloadTableViewData() {
        collectionView.reloadData()
    }
    
    func resetCollectionView() {
        collectionView.reloadData()
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        resetCollectionView()
    }

Upvotes: 1

Related Questions