I have a grouped tableview and the datasource looks as follows:
let customCell = UITableViewCell()
customCell.textLabel?.text = "this is a custom cell"
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellA", for: indexPath) as! CellA
cell.label.text = "dummy text"
switch indexPath.section {
case 0 :
switch indexPath.row {
case 0 : cell.label.text = "Foo"
case 1 : cell.label.text = "Bar"
default:
fatalError("Row does not exist")
}
case 1 :
switch indexPath.row {
case 0 : return customCell
default:
fatalError("Row does not exist")
}
default:
fatalError("Section does not exist")
}
return cell
}
func numberOfSections(in tableView: UITableView) -> Int { return 2 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0 : return 2
case 1 : return 1
default:
fatalError("Section does not exist")
}
}
customCell
dequeueReusableCell(identifier:,indexPath:)
"dummy text"
dequeueReusableCell(identifier:)
indexPath
indexPath
So you are doing almost correct, your customCell
is also getting added to your tableView
. But what is happening here is, at first you are dequeueing
a cell in cellForRowAt
and then checking for section
and returning the cell
. So Your customCell
for indexPath.section = 1
is added but the dequeued
cell present on top of it. You can debug the view hierarchy
and see the magic.
Now you have to move your cell
creation to individual section
and return from there, like below, it should work:
switch indexPath.section {
case 0:
let cell = tableVIew.dequeueReusableCellWithIdentifier("cellA", forIndexPath: indexPath) as! cellA
cell.textLabel?.text = "dummy text"
switch indexPath.row {
case 0 :
cell.textLabel?.text = "Foo"
return cell
case 1 :
cell.textLabel?.text = "Bar"
return cell
default:
fatalError("Row does not exist")
}
case 1:
switch indexPath.row {
case 0 :
return customCell
default:
fatalError("Row does not exist")
}
default:
fatalError("Section does not exist")
}