无法设置 UITableViewCell 的详细信息标签



我正在尝试创建一个包含UITableview的屏幕,该屏幕由部分和不同的行类型组成(如下所示(。问题是,当尝试更改频率单元格中"详细信息"标签的值时,它说这是一个仅获取属性。频率单元格设置为在情节提要中键入"正确的细节"。

我的代码是:

    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!

另外,如何避免在最后一行强制打开单元格的包装?我尝试初始化一个空的 TableViewCell,但似乎没有空的初始值设定项。

首先,您应该从表视图中请求一个单元格,如下所示:

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

还有其他indexPath参数,此方法保证返回非可选的 UITableViewCell 实例。这也将使单元实例成为非可选的,因此您不必解开包装。您应该阅读这两种方法的区别,有很多关于它的信息。

您遇到的另一个问题:detailTextLabel 是一个 UILabel 实例,因此您需要通过 text 属性设置其内容。喜欢这个:

cell.detailTextLabel?.text = "test"

在有错误的行中,您正在为cell?.detailTextLabel?分配一个String,这是UILabel?的实例,而不是String。 要为标签的文本分配String,请执行cell?.detailTextLabel?.text = "test"

此外,detailTextLabel?属性是 readonly ,这意味着您很遗憾无法为其分配自己的UILabel?实例。 但是,您可以做的是设置所需的任何属性,以便根据自己的喜好对其进行自定义。 所以你可以做cell?.detailTextLabel?.backgroundColor =cell?.detailTextLabel?.font =等。

至于打开单元格,您应该将单元格与

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

此方法不返回可选。

最新更新