Swift UITableViewCell detailTextLabel.text抛出错误'致命错误:无法解包Optional.None'

jbm*_*223 6 uitableview ios swift

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

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

永远不会被调用,因此单元格永远不会被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")
Run Code Online (Sandbox Code Playgroud)

以下是该方法的控制台输出:

start load
1
2
done load
start TableViewCellForRowAtIndexPath
2
fatal error: Can't unwrap Optional.None
(lldb) 
Run Code Online (Sandbox Code Playgroud)

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

单元格不是在故事板中创建的.我使用了初始化单元格或注册了它的类tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellSubtitle")

rde*_*mar 9

我假设你在故事板中创建了你的单元格,这就是为什么永远不会调用"if"子句的原因.您只需要在故事板的检查器中将单元格的样式更改为"Subtitle"(并删除该if子句).

  • @ jbman223,使用该方法只能为您提供"基本"类型单元格.只需删除该行,然后您的代码就可以工作,因为初始出列将返回一个nil单元格,这将导致输入if子句. (5认同)