Swift – 从multidimensional array中填充多个部分的TableViews

我是Swift的初学者,至less了解了如何填充UITableView的基础知识。 我现在被困在用字典提供的数据填充多个部分。

我有一个多维词典分配对象类别:

var categoryDict:[String:[AnyObject]] = ["Category A": ["Object 1","Object 2"], "Category B":["Object 3"]] 

现在我想填充我的TableView,以便它显示如下所示:

  • 类别A

    • 对象1
    • 对象2
  • B类

    • 对象3

到目前为止,我能够创build一个类别数组来返回节的数量,以及计算存储在字典中的数组,以获得每个特定类别中的行数。 现在我完全停留在用表格和行填充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 } 

首先:字典是存储表格视图内容的不好的select。 字典本身是无序的,所以你必须继续sorting键。 如果您的数据超出了一小部分的sorting过程将需要相当多的时间。

如果你打算使用一个字典,你应该重构你的代码,这样你就可以保存已sorting的键,并重复使用它们,除非字典改变了。 我会这样做,所以你添加一个setter方法的字典,并始终使用该setter来更改字典。 setter方法将重新生成sorting的键。 这样你只需要在字典改变的时候对键进行sorting。 (但更好的是完全摆脱字典。)

我会build议创build一个包含sectionTitle StringsectionEntries数组的Section对象。 然后使表视图数据是一个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[category]! let anObject = aCategoryEntry[row] // let cell.textLabel.text = anObject return cell }