I am a beginner in Swift and have managed to understand at least the very basics of how to populate a UITableView. I am stuck now at populating multiple sections with data provided out of a dictionary.
I have a multidimensional Dictionary that assigns Objects to Categories:
var categoryDict:[String:[AnyObject]] = ["Category A": ["Object 1","Object 2"], "Category B":["Object 3"]]
Now I want to populate my TableView, so that it shows something like this:
Category A
- Object 1
- Object 2
Category B
- Object 3
So far I am able to create an array of categories to return the number of sections as well as to count the arrays stored in the dictionary to get the number of rows in each specific category. Now I am completely stuck at populating the TableView with sections and rows. How can I do this? Thank you very much!
My code so far:
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
}