【问题标题】:CustomTableViewCell yeilding nil?CustomTableViewCell 屈服于零?
【发布时间】:2019-09-09 07:16:23
【问题描述】:

我和here 有同样的问题,但无法让他们的解决方案发挥作用。

每次运行时:

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!
}

【问题讨论】:

  • let cell = commentTableViewCell() 行不正确。您需要从表格视图中正确地使单元格出列。您的方式不是从情节提要(或 xib)创建单元格,因此没有设置任何插座,因此为零。
  • 查看众多的 Swift 表格视图教程中的任何一个。您会发现很多关于如何实现cellForRowAt 方法的示例。这包括您链接的问题。

标签: ios swift uitableview


【解决方案1】:

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

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


viewDidLoad 中的 Xib 单元格

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

你必须有

commentTableViewCell.swift

commentTableViewCell.xib

对于原型细胞

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2012-11-10
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多