Swift tableView.dequeueReusableCell从不返回Nil

jbm*_*223 6 uitableview ios swift

这是我生成表格视图的Swift代码.我正在尝试设置带有详细标签的tableView.问题是永远不会调用以下代码.

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

以下是该方法所需的代码:

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    println("start TableViewCellForRowAtIndexPath")
    var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("CellSubtitle", forIndexPath: indexPath) 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. 
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?

Mic*_*lum 6

只要您注册一个单元类以供重用,或者在Interface Builder中提供原型,您就不需要使用此出列方法检查单元格是否为nil.

let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle", forIndexPath: indexPath) as! UITableViewCell
Run Code Online (Sandbox Code Playgroud)

但是,如果要继续手动初始化单元格,则可以使用以下出列方法.(请记住,这是旧的方式)

let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle") as? UITableViewCell
Run Code Online (Sandbox Code Playgroud)

然后,就初始化detailTextLabel而言,您不必这样做.它内置在单元格中,通过指定单元格的样式应该是副标题,将为您设置该标签.

请注意,Swift 2中不需要强制转换.