[英]UITableViewController with custom data source not showing cells
I currently have a UITableViewController that sets up a custom data source in its init function: 我目前有一个UITableViewController,它在其init函数中设置了一个自定义数据源:
class BookmarkTableViewController: UITableViewController {
var date: Date
// MARK: - Init
init(date: Date, fetchAtLoad: Bool) {
self.date = date
super.init(style: .plain)
self.tableView.dataSource = BookmarkDataSource(date: date)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
// ...
}
The custom data source is as follows: 定制数据源如下:
class BookmarkDataSource: NSObject {
let date: Date
init(date: Date) {
self.date = date
super.init()
}
}
// MARK: - UITableViewDataSource
extension BookmarkDataSource: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "Test content"
return cell
}
}
However when I run on the simulator or on a device nothing shows up in the table view. 但是,当我在模拟器或设备上运行时,表视图中没有任何显示。 Does anyone know what I'm missing?
有人知道我在想什么吗?
Note: I'm using Xcode 8.0 Beta and Swift 3. 注意:我正在使用Xcode 8.0 Beta和Swift 3。
You need to store a strong reference to your BookmarkDataSource object. 您需要存储对BookmarkDataSource对象的强引用。 The dataSource of tableView becomes nil with the code you posted.
tableView的dataSource与您发布的代码一起变为nil。
class BookmarkTableViewController: UITableViewController {
var date: Date
var dataSource:BookmarkDataSource
// MARK: - Init
init(date: Date, fetchAtLoad: Bool) {
self.date = date
super.init(style: .plain)
dataSource = BookmarkDataSource(date: date)
self.tableView.dataSource = dataSource
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
// ...
}
I think your cells aren't being properly instantiated. 我认为您的单元格未正确实例化。
Try replacing 尝试更换
let cell = UITableViewCell()
with 与
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.