ios - TableView reloadData 对自定义 dataSource 类不执行任何操作

标签 ios swift uitableview

我创建了一个自定义 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/

相关文章:

ios - draw func 不适用于 Storyboard 中的按钮

ios - InstantiateViewController(标识符 :creator:)' is only available in iOS 13. 0 或更新版本

ios - 使用 Swift 以编程方式向按钮添加约束

ios - 将 UITextField 的输入添加到数组中

ios - 尝试在 UIView 中添加 Tableview。我在这里做错了什么?

ios - UIRefreshControl 在 Xamarin iOS 上崩溃

ios - NSUserDefault vs Global Variable vs CD vs Singleton——一个具体的例子

ios - UICollectionView 没有出现在模拟器中

swift - 是否存在确定类型应该用字符串初始化的协议(protocol)?

ios - contentView 不在 iOS 6 UITableViewCell 原型(prototype)单元格中缩进