I am trying to create a custom TableView
that will output custom cells depending on the keys contained in a Dictionary
. I have created classes and outlets for each custom cell, but when I build and run; the same custom cell is displayed multiple times. I have the correct number of cells being displayed (i.e. the same as number of keys present in the dictionary) but I can't seem to differentiate between outputted cells.
Here is my code:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataDict.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (dataDict.indexForKey("Number") != nil) {
let firstcell:MyFirstCell = self.scanConfirmTable.dequeueReusableCellWithIdentifier("scanfirst", forIndexPath: indexPath) as! MyFirstCell
return firstcell
}
else if (dataDict.indexForKey("Social") != nil) {
let secondcell:MySecondCell = self.scanConfirmTable.dequeueReusableCellWithIdentifier("scansecond", forIndexPath: indexPath) as! MySecondCell
return secondcell
}
else {
let emptycell:ScanEmptyCell = self.scanConfirmTable.dequeueReusableCellWithIdentifier("scanemptycell", forIndexPath: indexPath) as! ScanEmptyCell
return emptycell
}
I have searched previous posts on here and found an option to use something like:
let currentTag = dataDict[indexPath.row]
But I am getting an error:
Cannot subscript a value of type '[String:String]' with an index type 'Int'.
Any help would be hugely appreciated!
Instead of using Dictionary
try to use Array
that contains your all keys with sorted and use that array with tableViewDataSource
methods.
var keysArray = [String]()
keysArray = Array(dataDict.keys).sorted(<)
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.keysArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (keysArray[indexPath.row] == "Number") {
let firstcell:MyFirstCell = self.scanConfirmTable.dequeueReusableCellWithIdentifier("scanfirst", forIndexPath: indexPath) as! MyFirstCell
return firstcell
}
else if (keysArray[indexPath.row] == "Social") {
let secondcell:MySecondCell = self.scanConfirmTable.dequeueReusableCellWithIdentifier("scansecond", forIndexPath: indexPath) as! MySecondCell
return secondcell
}
else {
let emptycell:ScanEmptyCell = self.scanConfirmTable.dequeueReusableCellWithIdentifier("scanemptycell", forIndexPath: indexPath) as! ScanEmptyCell
return emptycell
}