How to Set UITableViewCellStyleSubtitle and dequeueReusableCell in Swift?

前端 未结 13 1031
攒了一身酷
攒了一身酷 2020-12-01 05:03

I\'d like a UITableView with subtitle-style cells that use dequeueReusableCellWithIdentifier.

My original Objective-C code was

13条回答
  •  自闭症患者
    2020-12-01 05:24

    Keep in mind that UITableView is defined as an optional in the function, which means your initial cell declaration needs to check for the optional in the property. Also, the returned queued cell is also optional, so ensure you make an optional cast to UITableViewCell. Afterwards, we can force unwrap because we know we have a cell.

    var cell:UITableViewCell? = 
    tableView?.dequeueReusableCellWithIdentifier(reuseIdentifier) as? UITableViewCell
    if (cell == nil)
    {
       cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, 
                    reuseIdentifier: reuseIdentifier)
    }
    // At this point, we definitely have a cell -- either dequeued or newly created,
    // so let's force unwrap the optional into a UITableViewCell
    cell!.detailTextLabel.text = "some text"
    
    return cell
    

提交回复
热议问题