代码之家  ›  专栏  ›  技术社区  ›  Tony Merritt

如何将单元格数据放入单元格类而不是VC类?,iOS,斯威夫特

  •  -1
  • Tony Merritt  · 技术社区  · 6 年前

    我想把一些代码从我的cell for row移到它自己的cell类中,使它更整洁一些。

    我的一系列字典。

    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牢房。

    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移到cell类的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
    }
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Paulw11    6 年前

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

    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 = ""
                }
            }
        }
    }
    
        2
  •  0
  •   Jaydeep Vora    6 年前

    在下面写入函数 resultsCell

    func setInfo(appCell: [String : Any]) {
    
        let imageUrl = appCell["artwork"] as? String
    
        if imageUrl == nil {
            iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
        }else {
            iconPicture.sd_setImage(with: URL(string: "\(imageUrl!)"))
        }
    
        titleLabel.text = appCell["name"] as? String
        descriptionLabel.text = appCell["desc"] as? String
        priceLabel.text = appCell["price"] as? String
        let rating = appCell["rating"]
        if rating != nil {
            ratingLabel.text = "Rating: \((rating!))"
        }
    }
    

    现在将数组值传递给,如下所示 cellForRowAt 方法。

    let appCell = appInfo[indexPath.row]
    cell.setInfo(appCell: appCell)
    
        3
  •  0
  •   Enea Dume    6 年前
    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(_ appCell: [String:Any], inIndexPath: IndexPath, _ cntrl: UIViewController) {
    
    
            let imageUrl = appCell["artwork"] as? String
    
            if imageUrl == nil {
                iconPicture.image = #imageLiteral(resourceName: "NoAlbumImage")
            }else {
                iconPicture.sd_setImage(with: URL(string: "\(imageUrl!)"))
            }
    
            titleLabel.text = appCell["name"] as? String
            descriptionLabel.text = appCell["desc"] as? String
            priceLabel.text = appCell["price"] as? String
            let rating = appCell["rating"]
            if rating != nil {
                ratingLabel.text = "Rating: \((rating!))"
            }
        }
    }
    

    在tableView的委托中写入:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        if let cell = tableView.dequeueReusableCell(
          withIdentifier: "your Results Cell ID from storyboard",
          for: indexPath) as? resultsCell {
                let appCell = appInfo[indexPath.row]
            cell.setInfo(appCell, inIndexPath: indexPath, self)
    
            return cell
    
        }else {
            return UITableViewCell()
        }
    }
    

    为了更进一步,只需删除字典数组,最好使用 structs 属于 models .