我是 Swift 的初学者,并且已经设法至少了解如何填充 UITableView 的基础知识。我现在陷入了用字典提供的数据填充多个部分的困境。
我有一个多维字典,它将对象分配给类别:
var categoryDict:[String:[AnyObject]] = ["Category A": ["Object 1","Object 2"], "Category B":["Object 3"]]
现在我想填充我的 TableView,以便它显示如下内容:
类别A
- 对象 1
- 对象 2
B 类
- 对象 3
到目前为止,我能够创建一个类别数组来返回部分数量,并对字典中存储的数组进行计数以获取每个特定类别中的行数。现在我完全陷入用部分和行填充 TableView 的困境。我怎样才能做到这一点?非常感谢!
到目前为止我的代码:
var categoryList:[String] = [String]()
var categoryDict:[String:[AnyObject]] = ["Category A": ["Object 1","Object 2"], "Category B":["Object 3"]]
func getLists() {
categoryList = Array(categoryDict.keys)
categoryList.sortInPlace(before)
}
// Sort Array
func before(value1: String, value2: String) -> Bool {
return value1 < value2;
}
func getNumberOfEntrysInSection (Section: Int) -> Int {
let category:String = categoryList[Section] //Get Category for Index in CategoryList
let value:[AnyObject] = categoryDict[category]! //Get Value for this specific Category
let number = value.count
return number
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
getLists()
return categoryList.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return getNumberOfEntrysInSection(section)
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return categoryList[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("BufferCell", forIndexPath: indexPath)
???
return cell
}
最佳答案
首先:字典对于存储 TableView 内容来说是一个糟糕的选择。字典本质上是无序的,因此您必须不断对键进行排序。如果您的数据超出了少量项目,则排序过程将花费相当长的时间。
如果你无论如何都要使用字典,你应该重构你的代码,以便保留排序的键并一遍又一遍地使用它们,除非字典发生变化。我会这样做,以便您向字典添加一个 setter 方法,并始终使用该 setter 来更改字典。 setter 方法将重新生成排序后的键。这样,如果字典发生变化,您只需对键进行排序。 (但最好完全摆脱字典。)
我建议创建一个 Section
对象,其中包含一个sectionTitle String
和一个sectionEntries
数组。然后将 TableView 数据设置为Section 对象的数组。
但是,既然您有字典,我将向您展示如何使该代码工作。
您需要有关 cellForRowAtIndexPath
方法的帮助。你快到了。您只需使用 indexPath 部分和行获取数据结构中适当的条目。像这样的事情:
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("BufferCell",
forIndexPath: indexPath)
let section = indexPath.section
let row = indexPath.row
let categoryKey:String = categoryList[section]
let aCategoryEntry:[String] = categoryDict[categoryKey] as! [String]
let anObject = aCategoryEntry[row] //
let cell.textLabel.text = anObject
return cell
}
关于ios - Swift - 使用多维数组中的多个部分填充 TableViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113361/