我创建了一个自定义 UITableViewDataSource 类。初始化时,我将tableView的委托(delegate)和dataSource设置为self,但是当调用reloadData()时,没有调用任何dataSource方法,并且传入的tableView没有变化。 (为了清楚起见,我省略了下面的委托(delegate)代码。)
class TopicsDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
var topics: [String : Topic] = [:]
var cellConfigBlock: ((UserTopicCell, Topic) -> ())? = nil
var tableView: UITableView!
var user: User!
init(tableView: UITableView, user: User) {
super.init()
self.tableView = tableView
self.user = user
tableView.dataSource = self
tableView.delegate = self
self.getData() // Call reloadData
}
func getData() {
let rootRef = FIRDatabase.database().reference()
DispatchQueue.global(qos: .userInitiated).async {
let updateGroup = DispatchGroup()
for tid in self.user.topicIDs!.keys {
updateGroup.enter()
rootRef.child("topics/" + tid).observeSingleEvent(of: .value, with: { (snp) in
let newTopic = Topic(json: (snp.value as! [String : Any]), completion: {
updateGroup.leave()
})
self.topics.updateValue(newTopic!, forKey: snp.key)
})
}
updateGroup.notify(queue: .main, execute: {
// Notice: the dataSource reference of tableView is weak
self.tableView.reloadData()
})
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let topic = Array(topics.values)[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "topicCell") as! UserTopicCell
if let config = cellConfigBlock {
config(cell, topic)
}
cell.topic = topic
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return topics.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// Delegate Methods ...
}
最佳答案
那么,在这种情况下,您还必须自定义重新加载数据以及表格 View 的自定义数据源和自定义委托(delegate)。
关于ios - TableView reloadData 对自定义 dataSource 类不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42895922/