自定义UITableViewCell没有出现

时间:2016-02-28 00:23:55

标签: ios swift uitableview

我有一个UITableViewController的自定义单元格视图。我创建了一个空的Interface Builder文档,然后添加了一个Table View Cell,然后添加了一个标签。表视图单元格具有扩展UITableViewCell的相应类。 Interface Builder中的表视图单元格标签与我的自定义类

中的var链接(outet)
class MyTableViewCell: UITableViewCell {
    @IBOutlet var someLabel: UILabel!

问题是自定义单元格永远不会呈现,它总是空白的(我也尝试了背景颜色技巧)。我从未见过这个标签。事实上,标签始终为空。

在我UITableViewController的{​​{1}}中,我试过了

viewDidLoad()

以及

let nib = UINib(nibName: "MyTableCellView", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "myCell")

我也有

tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "myCell")

在运行时它会出列,因为override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! MyTableViewCell print("cellForRowAtIndexPath, cell = \(cell), someLabel = \(cell.someLabel)") return cell } 为非空,但cell为零。

自定义表格视图单元格渲染需要什么?

2 个答案:

答案 0 :(得分:0)

someLabel没有价值。尝试:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! MyTableViewCell
    cell.someLabel.text = "Put label text here"
    return cell
}

答案 1 :(得分:0)

我通常这样做。我在自定义表视图单元类中加载了xib文件。

class MyTableViewCell: UITableViewCell {

    @IBOutlet weak var label: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        xibSetup()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        xibSetup()
    }

    func xibSetup() {
        cell = loadViewFromNib()
        cell.frame = self.bounds
        cell.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
        addSubview(cell)
    }

    func loadViewFromNib() -> UITableViewCell {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: "MyTableViewCell", bundle: bundle)
        let cell = nib.instantiateWithOwner(self, options: nil)[0] as! UITableViewCell
        return cell
    }

}

同时:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! MyTableViewCell
    print("cellForRowAtIndexPath, cell = \(cell), someLabel = \(cell.someLabel)")
    return cell
}

另一件事是将MyTableViewCell.xib文件中的文件所有者设置为MyTableViewCell类。

相关问题