首页 > 解决方案 > 如何将单元格数据放入单元格类而不是 VC 类?,iOS,Swift

问题描述

我想将一些代码从我的单元格中移到它自己的单元格类中,使其更整洁一些。

这是我的代码。

我的字典数组。

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

我的细胞课。

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() {


  }
}

我的 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()
}
}

我想将我的 cell.label.text 从 VC 移动到单元类中的 set info 函数。

这是我的 JSON 解码和结构。

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()
}
}

结构..

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
}

标签: iosswiftuitableviewcell

解决方案


首先,我会用结构数组替换字典数组;这样你就不需要所有的向下转换:

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
}

然后您可以使用didSet结构中的值更新您的单元格

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 = ""
            }
        }
    }
}

推荐阅读