我正在嘗試按第一個字符對名稱進行分組,并使用新的 UITableViewDiffableDataSource 在 ViewController 中顯示它。(例如聯系人應用程式)
**A** (header title)
Apple
Amazon
**B** (header title)
Broadcom
Bezoz
**C** (header title)
Calderon
下面是我使用舊 DataSource 方法的代碼。
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 方法設定它。有沒有辦法設定部分和行?
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!
uj5u.com熱心網友回復:
洗掉Section
列舉。這些部分是排序的鍵。
dataSource
用這種型別宣告
var dataSource: UITableViewDiffableDataSource<Character, Contacts>!
并創建快照
var snapshot = NSDiffableDataSourceSnapshot<Character, Contacts>()
snapshot.appendSections(sortedDictKeys)
sortedDictKeys.forEach { letter in
snapshot.appendItems(dict[letter]!, toSection: letter)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470574.html
標籤:迅速 合适的视图 合适的视图节标题 可区分数据源 uitableviewdiffabledatasource