大家好,这是我的第一篇文章。
我试图在 TableView
中显示动态数据: 我在 Dictionary
中有数据像这样var dizionarioComuni : Dictionary<Character, Array<ComuneModel>> = [:]
对象 ComuneModel 是一个自定义模型,带有 nomeComune、numAbitanti 等数据
在TableView
我写了这段代码来获取部分的编号并且它有效
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//tot valori nel dictionary
dizionarioComuni.count
}
字典的键是字符,因为我想使用这些键作为该部分的标题。
问题是:我怎样才能得到 numberOfRowsInSection
在 TableView 的方法中?该方法的签名是这样的
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
anf 取一个整数,但我的键是字符。我尝试使用此代码访问字典的所有键
var keys = dizionarioComuni.keys
我可以遍历键,但我如何从对象列表(ComuniModel)中特定索引(部分:Int)的特定键访问,这是方法的参数?
我搜索了类似的问题,但答案并没有谈到这个案例。 非常感谢
最佳答案
Swift 字典是无序的,因此您需要维护一个单独的排序键列表并使用它来访问您的数据。
var sortedKeys = dizionarioComuni.keys.sort()
然后 numberOfRowsInSection
变成:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dizionarioComuni[sortedKeys[section]]?.count ?? 0
}
注意:任何时候您的键列表发生变化,您都需要重新加载表中的数据。
class MyTableViewController: UITableViewController {
var sortedKeys = [Character]() {
didSet {
if oldValue != sortedKeys {
// reload tableView
tableView.reloadData()
}
}
}
var dizionarioComuni = [Character: [ComuneModel]]() {
didSet {
sortedKeys = dizionarioComuni.keys.sort()
}
}
}
关于ios - 字典中的快速 numberOfRowsInSection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39305783/