首页 > 解决方案 > CustomTableViewCell 屈服于零?

问题描述

我和这里有同样的问题但是无法使他们的解决方案起作用。

每次运行时:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = commentTableViewCell()

    print("called T")
    if arrayOfComments.count != 0 {
        do {
            let url = URL(string: (arrayOfComments[indexPath.row].user.profileImageUrlString)!)
            let imageData = try Data(contentsOf: url!)
            let image = UIImage(data: imageData)

            cell.dateOfComment.text = "testText"//crash here
        } catch {
            print(error, ": Failed in do block converting image")
        }
    }

    return cell
}

我得到:

线程 1:致命错误:在隐式展开可选值时意外发现 nil

自定义单元:

import UIKit

class commentTableViewCell: UITableViewCell {

    @IBOutlet weak var dateOfComment: UILabel!
    @IBOutlet weak var commentText: UILabel!
    @IBOutlet weak var profImage: UIImageView!
    @IBOutlet weak var username: UILabel!
}

标签: iosswiftuitableview

解决方案


为您的单元格设置标识符并替换

let cell = commentTableViewCell() // this loads the cell class without attached IB outlets 

let cell = tableView.dequeueReusableCell(withIdentifier:"cellId", for: indexPath) as! commentTableViewCell

还有这个

let imageData = try Data(contentsOf: url!)
    

阻塞主线程考虑使用SDWebImage


对于 Xib 细胞viewDidLoad

tableView.register(UINib(nibName: "commentTableViewCell", bundle: nil), forCellReuseIdentifier: "commentCell")
 

你必须有

commentTableViewCell.swift

commentTableViewCell.xib

对于原型细胞

只需在没有寄存器的情况下设置标识符,因为在这种情况下它会自动完成


推荐阅读