ios - Swift UITableViewCell detailTextLabel.text 抛出错误 'fatal error: Can' t unwrap Optional.None'

标签 ios uitableview swift

这是生成表格 View 的 Swift 代码。我正在尝试设置带有详细信息标签的 tableView。我相信问题的产生是因为

if (cell == nil) {
            println("1")
            cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "CellSubtitle")
            //cell = tableViewCell
        }

永远不会被调用,因此单元格永远不会使用 UITableViewCellStyle.Subtitle 样式进行初始化。以下是该方法所需的代码:

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    println("start TableViewCellForRowAtIndexPath")
    var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("CellSubtitle") as UITableViewCell
    if (cell == nil) {
        println("1")
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "CellSubtitle")
        //cell = tableViewCell
    }

    cell.textLabel.text = instructions[indexPath.row].text
    println("2")
    //cell.detailTextLabel
    cell.detailTextLabel.text = "HI"
    println("3")

这是该方法的控制台输出:

start load
1
2
done load
start TableViewCellForRowAtIndexPath
2
fatal error: Can't unwrap Optional.None
(lldb) 

如何初始化 detailTextLabel 以插入文本?当我尝试为标签设置文本时,我收到 fatal error: Can't unwrap Optional.None。为什么我会收到此错误?

单元格不是在 Storyboard 中创建的。我使用 tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellSubtitle")

初始化单元格或注册它的类

最佳答案

我假设您在 Storyboard中制作了单元格,所以这就是为什么永远不会调用“if”子句的原因。您只需要在 Storyboard的检查器中将单元格的样式更改为“副标题”(并删除该 if 子句)。

关于ios - Swift UITableViewCell detailTextLabel.text 抛出错误 'fatal error: Can' t unwrap Optional.None',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24190284/

相关文章:

ios - 从 iPad 应用程序发送电子邮件后,sqlite 数据库没有数据

ios - 自定义 FUIAuthPickerViewController

ios - 在添加新值之前如何检查数组是否具有相同的对象值

ios - 从表中删除 managedObject 但如何删除附加图像?

ios - 串行队列/专用调度队列如何知道任务何时完成?

arrays - swift 中的核心数据数组

objective-c - iOS ViewController 属性在推送新 Controller 并在导航 Controller 中再次返回后消失

iOS:在 xml 解析完成之前创建 TableView

ios - 如何修改 UITableview 最后一个单元格中按钮的尾随空格?

iOS TableView 如何访问自定义单元格变量