swift - 如何在静态 UITableView 中设置 detailTextLabel.text?

标签 swift uitableview

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

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


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

Image 1


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

Image 2

这是我试过的:

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
}

但是,它返回一个错误:

*** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:],
/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.6.21/UITableView.m:6600
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier user_Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

最佳答案

这是一个静态表。修改单元格对于静态表的工作方式不同。您必须实现 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
}

关于swift - 如何在静态 UITableView 中设置 detailTextLabel.text?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42451734/

相关文章:

iOS 应用程序不断崩溃,但在现场测试中运行良好

ios - 无法以编程方式注册在 UIViewController 中创建的 TableView 的 TableCell

ios - 如何在底部插入带有动画的 UITableViewCell?

ios - 动态调整具有嵌入 swift 的 TextView 的 IOS tableview 单元格

ios - 将 UITableView 和截面方向/对齐方式设置为 RTL(从右到左)

iOS iMessage 应用扩展 - 复制 iMessage 贴纸应用行为

ios - SpeechKit Pod for Swift 导致未声明的类型错误

objective-c - 将 Objective-C 转换为 Swift - 无符号类型使用什么?

ios - 如何在TableViewController中实现后退导航按钮?

ios - 使用两个字符串生成并读取 QR