Разделы в UITableView с пользовательскими ячейками
Пока у меня есть следующий код.
var someData = [SomeData]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! Cell1
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? Cell2
let someData = [indexPath.row]
//Set up labels etc.
return cell!
}
}
Мне нужен Cell1, который является статической ячейкой и всегда будет оставаться в indexPath 0, чтобы быть в разделе с именем "Section1", например, и все Cell2 должны быть в разделе с именем "Section2"
Другие источники данных и методы делегирования;
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return someData.count
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Section1" }
else {
return "Section2"
}
}
Это возвращает мне все, что мне нужно для первого раздела, однако, когда дело доходит до второго раздела (из-за кода внутри cellForRowAtIndex где-то) раздел 2 содержит Cell2 в indexPath 0.
Любая помощь с благодарностью.
1 ответ
Решение
Первопричина:
В cellForRowAtIndexPath
проверить indexPath.section
вместо indexPath.row
Fix:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! Cell1
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? Cell2
let someData = [indexPath.row]
//Set up labels etc.
return cell!
}
}