Search code examples
iosswiftuitableviewcell

How can I put cell data into a cell class instead of VC class?, iOS, Swift


I want to move some code from my cell for row into its own cell class to make it a little tidier.

Here is my code.

My array of dictionaries.

var appInfo = [[String:Any]]()

My cell class.

class resultsCell: UITableViewCell {

@IBOutlet weak var iconPicture: UIImageView!    
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!



func setInfo() {


  }
}

My VC cellForRow.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if let cell = tableView.dequeueReusableCell(withIdentifier: "resultsCell", for: indexPath) as? resultsCell {

        let appCell = appInfo[indexPath.row]
        let imageUrl = appCell["artwork"] as? String

        if imageUrl == nil {
            cell.iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
        }else {
            cell.iconPicture.sd_setImage(with: URL(string: "\(imageUrl!)"))
        }

        cell.titleLabel.text = appCell["name"] as? String
        cell.descriptionLabel.text = appCell["desc"] as? String
        cell.priceLabel.text = appCell["price"] as? String
        let rating = appCell["rating"]
        if rating != nil {
            cell.ratingLabel.text = "Rating: \((rating!))"
        }

        return cell

    }else {
        return UITableViewCell()
}
}

I want to move my cell.label.text's from the VC to the set info function in the cell class.

Here is my JSON decoding and structs.

import Foundation

var appInfo = [[String:Any]]()

class searchFunction {

static let instance = searchFunction()

func getAppData(completion: @escaping (_ finished: Bool) -> ()) {
guard let url = URL(string: BASE_ADDRESS) else { return }

URLSession.shared.dataTask(with: url) { (data, response, err) in
    guard let data = data else { return }
    do {
        let decoder = JSONDecoder()
        let appData = try decoder.decode(Root.self, from: data)
        appInfo = []
        for app in appData.results {
            let name = app.trackName
            let desc = app.description

            guard let rating = app.averageUserRating else { continue }
            let price = app.formattedPrice
            let artwork = app.artworkUrl60.absoluteString


            let appInd = ["name":name, "desc":desc, "rating":rating, "price":price, "artwork":artwork] as [String : Any]

            appInfo.append(appInd)
        }
        completion(true)
    }catch let jsonErr {
        print("Error seroalizing json", jsonErr)
    }
    }.resume()
}
}

Structs..

import Foundation


struct Root: Decodable {
var results: [resultsFull]
}

struct resultsFull: Decodable {
var trackName: String
var description: String
var formattedPrice: String
var averageUserRating: Double?
var artworkUrl60: URL
}

Solution

  • First, I would replace that array of dictionaries with an array of structs; that way you don't need all of that downcasting:

    struct AppInfo {
        var artwork: String?
        var title: String?
        var description: String?
        var price: String?
        var rating: String?
    }
    
    
    var appInfo = [AppInfo]()
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: "resultsCell", for: indexPath) as! ResultsCell 
    
        cell.appInfo = self.appInfo[indexPath.row]
    
        return cell
    }
    

    Then you can use didSet to update your cell with the values from the struct

    class ResultsCell:UITableViewCell {
    
        @IBOutlet weak var iconPicture: UIImageView!
        @IBOutlet weak var titleLabel: UILabel!
        @IBOutlet weak var descriptionLabel: UILabel!
        @IBOutlet weak var priceLabel: UILabel!
        @IBOutlet weak var ratingLabel: UILabel!
    
        var appInfo: AppInfo {
            didSet {
                iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
                if let artwork = appInfo.artwork, let artworkURL = URL(string: artwork) {
                    iconPicture.sd_setImage(with: artworkURL)
                }
    
                titleLabel.text = appInfo.title ?? ""
                descriptionLabel.text = appInfo.description ?? ""
                priceLabel.text = appInfo.price ?? ""
                if let rating = appInfo.rating {
                    ratingLabel.text = "Rating: \(rating)")
                } else {
                    ratingLabel.text = ""
                }
            }
        }
    }