首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在UITableViewDiffableDataSource中是否有匹配节数匹配字典键计数的方法?

在UITableViewDiffableDataSource中是否有匹配节数匹配字典键计数的方法?
EN

Stack Overflow用户
提问于 2022-05-01 04:28:36
回答 1查看 75关注 0票数 1

我试图按第一个字符对名称进行分组,并使用新的ViewController (例如联系人应用程序)将其显示在UITableViewDiffableDataSource中。

代码语言:javascript
复制
**A** (header title) 
Apple 
Amazon
**B** (header title)
Broadcom
Bezoz
**C** (header title)
Calderon 

下面是我使用旧的DataSource方法的代码。

代码语言:javascript
复制
class ViewController: UITableViewDelegate, UITableViewDataSource {
    var tableView = UITableView()
    
    // Data Set for TableView
    var dict = [Character: [Contacts]]() // e.g. ["A": ["Apple", "Amazon"], "B": ["Broadcom, Bezoz"]...]
    var sortedDictKeys = [Character]() // e.g. ["A", "B", "C"]
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dict[sortedDictKeys[section]].count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return sortedDictKeys.count // returns 3 
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return String(viewModel.sortedBreedsKeys[section])
    }

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.text = sortedDictKeys[section]
    }
}

使用旧的UITableViewDataSource,我可以获得视图,但是如何使用Diffable方法来设置它。有办法设置区段和行吗?

代码语言:javascript
复制
class ViewController: UITableViewDelegate {
    enum Section: CaseIterable {
        case main
    }

    var tableView = UITableView()

    // Data Set for TableView
    var dict = [Character: [Contacts]]() // e.g. ["A": ["Apple", "Amazon"], "B": ["Broadcom, Bezoz"]...]
    var sortedDictKeys = [Character]() // e.g. ["A", "B", "C"]

    var dataSource: UITableViewDiffableDataSource<Section, Contacts>!
    var snapshot = NSDiffableDataSourceSnapshot<Section, Contacts>()

    func viewDidLoad() {
 
        dataSource = UITableViewDiffableDataSource.init(tableView: self.tableView, cellProvider: { tableView, indexPath, contact in
            return UITableViewCell()
        })
    }

    // MARK - TODO - How do I define the snapshot and append sections to reuse section in the snapshot?
}

Appreciate the help! 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-01 07:01:37

删除Section枚举。这些部分是排序的键。

使用以下类型声明dataSource

代码语言:javascript
复制
var dataSource: UITableViewDiffableDataSource<Character, Contacts>!

并创建快照。

代码语言:javascript
复制
var snapshot = NSDiffableDataSourceSnapshot<Character, Contacts>()
snapshot.appendSections(sortedDictKeys)
sortedDictKeys.forEach { letter in
    snapshot.appendItems(dict[letter]!, toSection: letter)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72073998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档