【问题标题】:How can I set detailTextLabel.text in static UITableView?如何在静态 UITableView 中设置 detailTextLabel.text?
【发布时间】:2017-02-25 03:48:05
【问题描述】:

我正在尝试使用 Swift 3 以编程方式在 UITableView 中设置单元格的正确详细信息。

但是,我无法调用detailTextLabel.text 来设置它。


目前,我有这个屏幕。如图所示,我需要使用UserDefaults 值以编程方式设置Signed in as:


我还设置了单元格的标识符:

这是我尝试过的:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "user_Cell", for: indexPath)

    let prefs:UserDefaults = UserDefaults.standard
    let user = prefs.value(forKey: "USER") as? String

    cell.detailTextLabel?.text = user

    return cell
}

但是,它返回一个错误:

*** -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] 中的断言失败,
/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.6.21/UITableView.m:6600
*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无法使单元格出列 带有标识符 user_Cell - 必须为 标识符或连接故事板中的原型单元'

【问题讨论】:

  • 定义“完全错误”。
  • @rmaddy 我已经用收到的错误更新了我的问题
  • 你搜索过那个错误吗?之前已经被问过很多次了。
  • @rmaddy 问题是它是一个静态表,他试图在这里将其视为动态表。没有原型细胞;该表是静态的。
  • 在您的标题中添加“静态”只是为了帮助其他人在将来找到它。

标签: swift uitableview


【解决方案1】:

这是一个静态表。对于静态表,修改单元格的工作方式不同。您必须实现cellForRowAt: 并调用super 并返回结果cell。如果这是您要修改的一个特殊单元格,请修改它(使用indexPath 作为测试)。像这样:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = super.tableView(tableView, cellForRowAt: indexPath)
    if indexPath == IndexPath(row: 0, section: 0) { // double-check this
        let prefs = UserDefaults.standard
        if let user = prefs.value(forKey: "USER") as? String {
            cell.detailTextLabel?.text = user
        }
    }
    return cell
}

【讨论】:

  • 很好,很高兴你明白我的意思。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 2012-06-26
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
相关资源
最近更新 更多