为什么UITableView不调用我的customCell?

时间:2016-04-15 07:21:16

标签: ios iphone swift uitableview

我以编程方式创建了UITableView和UITableViewCell。在我的ViewController中 - viewDidLoad我这样做:

self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.registerClass(newsCell.self, forCellReuseIdentifier: "newsCell")

稍后将其用作:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as! newsCell

    return cell
}

我的newsCell课程(不久):

class newsCell: UITableViewCell {
    let scoreLabel = UILabel()

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    print("init")

    self.addSubview(self.scoreLabel)
}
}

但我甚至没有在日志上获得init,因此它根本不会调用我的自定义单元格。有什么问题?

1 个答案:

答案 0 :(得分:2)

请尝试以下代码:

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

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

并强制展开是危险的。你应该这样做:

if let cell = self.tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as? newsCell{}