1

我正在使用 Xcode7.2.1 iOS9.2 SDK。

使用右细节设置自定义单元格样式

  1. 注册单元笔尖:

代码:

self.TbuserList.registerNib(UINib.init(nibName: "UserCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "idUserList")
  1. 设置单元格 detailTextLabel 文本:

代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("idUserList",forIndexPath: indexPath ) as! UserCell
    //print(self.users)
    cell.textLabel?.text = self.users[indexPath.row]["nickname"] as? String
    cell.detailTextLabel?.text = (users[indexPath.row]["isConnected"] as! Bool) ? "Online" : "Offline"
    cell.detailTextLabel?.textColor = (users[indexPath.row]["isConnected"] as! Bool) ? UIColor.greenColor() : UIColor.redColor()
    return cell
}

在此处输入图像描述

注意:当我将单元格样式从“右细节”更改为“副标题”或“左细节”时,就可以了。

4

2 回答 2

1

由于您使用的是从 xib 文件创建的自定义单元格,我建议避免尝试使用默认单元格元素(textLabel 和 detailTextLabel),而只需添加创建所需单元格所需的视图。您可以向标准单元格添加其他视图,但要确保您的视图与现有的标准单元格视图一起使用可能会稍微复杂一些。如果标准单元格类型适合您的需要,您可以使用 tableView 而不是自定义 xib 文件注册 UITableViewCell 类。查看 Apple文档中的自定义单元格部分

于 2016-02-29T15:39:17.847 回答
0

我不使用 Storyboard,所以我不确定这是否对您有任何帮助,但我在自定义单元格中是这样的:

class CustomTableViewCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        //MARK: Setting ".value1" in super.init(style: .value1, ...) is the key to do this
        super.init(style: .value1, reuseIdentifier: reuseIdentifier)

        textLabel?.text = "Main Label"

        detailTextLabel?.text = "Detail Label"
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

只要您添加一个新的 Swift 文件并为您的自定义单元格注册相同的名称,它就应该可以工作。

于 2020-10-13T10:06:01.083 回答