Swift:不能以编程方式configuration自定义表格单元格? 初始化不被调用?

好吧,我正在试图添加内容到我的自定义tableview单元格编程方式展示在暴民最后一个问题在这里 – 斯威夫特:tableview单元格内容是每次重新加载一次又一次? 初始化func tableView()中的所有内容导致重叠。

我逐字逐字地跟着这个问题。 正确初始化UITableViewCell层次结构在我的自定义单元类(我在故事板中给出了一个名称),我有:

class EventTableCellTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // the common code is executed in this super call // code unique to CellOne goes here print("INIT") self.contentView.backgroundColor = UIColor.blackColor() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } 

而这个init不会被调用,因为没有打印。 错误来自我的主要VC func tableView()。 我本来有:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventTableCellTableViewCell // cell.eventTitle.text = names[indexPath.row] // cell.eventDescription.text = descriptions[indexPath.row] cell.contentView.clipsToBounds = false //cell UIX let eventTitleLabel = UILabel() let dateLabel = UILabel() let authorLabel = UILabel() let locationLabel = UILabel() let categoryView = UIImageView() //then I add everything 

但是,这不起作用,所以我看着其他职位,现在有:

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //var cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventTableCellTableViewCell var cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! UITableViewCell if (cell == nil) { cell = EventTableCellTableViewCell.init(style: .Default, reuseIdentifier: "eventCell") } 

我也试过没有indexPath。 现在我得到一个错误,单元格不能==零,不pipe我写的init没有被调用。

我怎样才能以编程方式configuration我的细胞?

如果单元格是在故事板中devise的,只调用init?(coder aDecoder: NSCoder) ,则init(style: style, reuseIdentifier:永远不会被调用。

您必须将Interface Builder中的单元格类设置为EventTableCellTableViewCell