[英]Custom UITableViewCell not appearing
我有一个带有自定义单元格视图的UITableViewController
。 我创建了一个空的Interface Builder文档,然后添加了一个Table View Cell,然后为其添加了标签。 表格视图单元格具有扩展UITableViewCell
的相应类。 Interface Builder中的Table View Cell的标签链接(输出)到我的自定义类中的var
class MyTableViewCell: UITableViewCell {
@IBOutlet var someLabel: UILabel!
问题在于自定义单元永远不会渲染,它始终是空白的(我也尝试过背景色技巧)。 我没看到标签。 实际上,标签始终为空。
在我的UITableViewController
的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
非空cell.someLabel
队,但是cell.someLabel
为nil。
具有自定义表格视图单元格渲染需要什么?
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
}
我通常这样做。 我将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类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.