【发布时间】:2015-05-19 23:45:51
【问题描述】:
考虑以下简单的视图控制器:
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var items = ["One", "Two", "Three"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
self.tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
cell.titleLabel!.text = self.items[indexPath.row]
return cell
}
}
以及自定义单元格视图:
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
}
此代码导致以下错误。
致命错误:在展开可选值时意外发现 nil
titleLabel 为零 - 不清楚原因。设置UITableViewCell(如textLabel)的默认属性就可以了。
我正在为自定义单元格使用笔尖。
标签和表格视图都正确连接到它们的IBOutlets。
原型单元格和自定义 nib 视图都被标记为具有 CustomTableViewCell 类。
我是 iOS 开发新手,我是否遗漏了一些明显的东西?
【问题讨论】:
-
这里的单元格不是零吗? (let cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell)
-
您注意到警告“/Main.storyboard:64: Prototype table cells must have reuse identifiers”?
-
@ThomasKilian 在属性检查器中添加重用标识符会删除警告,但不会影响问题。
-
@iOSfleer
cell不为零。例如,设置单元格的textLabel属性会导致标签正确显示在 UI 中。 -
如果您在 xib 文件中创建了单元格,则应注册 nib,而不是类(仅当单元格的子视图是在代码中创建时才注册类)。
标签: ios uitableview swift interface-builder