简体   繁体   English

表初始化后,dequeueReusableCell返回空单元格

[英]dequeueReusableCell returns empty cell after table initialization

I have a table view that is initialized with three rows when loaded. 我有一个表视图,该表视图在加载时初始化为三行。 Later, I want to extract cell data (from labels) and use it when that specific cell is selected by the user. 稍后,我想提取单元格数据(从标签中)并在用户选择特定单元格时使用它。

Even though initialization works well and I can see all the data being displayed, the dequeueReusableCell in the didSelectRowAt methods returns empty cells, with no data. 即使初始化工作正常并且我可以看到所有数据都在显示,但didSelectRowAt方法中的dequeueReusableCell返回空单元格,没有数据。

What is the problem? 问题是什么?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ArticleTableViewCell else {
        fatalError("Whoopse, dequeueing the cell failed")
    }
    let title = cell.articleLabel.text
    // Do other stuff

}

The title variable above will be empty, even though it's data is shown on the display. 上面的标题变量将为空,即使其数据显示在显示屏上。

Replace 更换

guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ArticleTableViewCell else {
    fatalError("Whoopse, dequeueing the cell failed")
}

with ( not recommended ) 与( 不推荐

guard let cell = tableView.cellForRow(at:indexPath) as? ArticleTableViewCell else {
    fatalError("Whoopse, dequeueing the cell failed")
}

but ##better## is to access the data source array with the clicked index 但是## better ##将使用单击的索引访问数据源数组

let item = arr[indexPath.row]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM