我有一个自定义的UITableViewCell子类,其中包含一个用于UILabel的简单IBOutlet设置。
class SegmentCell: UITableViewCell {
@IBOutlet weak var test: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
test.text = "Some Text"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我相信我已经正确设置了一切,按照其他答案的方法操作,但UILabel始终为nil。
视图控制器:
viewDidLoad:
self.tableView.registerClass(SegmentCell.self, forCellReuseIdentifier: "Cell")
cellForForAtIndexPath
的正确翻译应为cellForItemAtIndexPath
。func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! SegmentCell
return cell
}
- 单元格设置为自定义
- 重用标识符正确
- 单元格类是SegmentCell
- 表视图内容为动态原型
我漏掉了什么?
weak var
是关键 - 如果你的SegmentCell
是唯一持有对UILabel
的引用的东西,那么它不会增加保留计数,因此标签将被释放,因为没有人有强引用它。当你尝试设置.text
时,它已经消失了。 - Chris