简体   繁体   中英

Can't set Detail label of UITableViewCell

I am trying to create a screen with UITableview that consists of sections and different row types ( shown here ). Problem is, when trying to change the value of Detail label in Frequency cell, it says it's a get-only property. Frequency cell is set to type "Right Detail" in storyboard.

My code is:

    let frequencyCellID = "frequencyCell"
    let decksCellID = "decksCell"
    let pickerCellID = "pickerCell"
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell?

    switch (indexPath.section,indexPath.row){
    case (0,0): cell = tableView.dequeueReusableCellWithIdentifier(frequencyCellID)
        //line below shows error
        cell?.detailTextLabel? = "test"
    case (0,1): cell = tableView.dequeueReusableCellWithIdentifier(pickerCellID)
    case (1,0): cell = tableView.dequeueReusableCellWithIdentifier(decksCellID)
        cell?.detailTextLabel? = "test"
    default: break
    }
    return cell!

Also, how can I avoid force unwrapping the cell in last line? I tried to initialize an empty TableViewCell but there seems to be no empty initializer.

First of all, you should request a cell from a table view like this:

let cell = tableView.dequeueReusableCellWithIdentifier(frequencyCellID, forIndexPath: indexPath)

There's additional indexPath parameter, and this method guarantees to return a non-optional UITableViewCell instance. This will also make your cell instance non-optional, thus you won't have to unwrap it. You should read about the differences of those two methods, there's a lot of info about that.

Another problem you have: detailTextLabel is a UILabel instance, so you need to set its content through text property. Like this:

cell.detailTextLabel?.text = "test"

In the line with an error, you are assigning a String to cell?.detailTextLabel? which is an instance of UILabel? and not a String . To assign a String to the label's text, do cell?.detailTextLabel?.text = "test" .

Also, the detailTextLabel? property is readonly , which means you unfortunately cannot assign your own UILabel? instance to it. What you can do, though, is set whatever properties on it you need in order to customize it to your liking. So you can do cell?.detailTextLabel?.backgroundColor = or cell?.detailTextLabel?.font = , etc.

As for unwrapping the cell, you should get your cell with

let cell = tableView.dequeueReusableCellWithIdentifier(frequencyCellID, forIndexPath:indexPath)

This method doesn't return an optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM