Группировка UITableView, аналогично приложению Контакты на iPhone
Не могу разобраться, как реализована группировка например в приложении Контакты на iOS. У меня есть массив объектов - друзей и два массива: 1ый с первыми буквами фамилий, 2ой с количеством друзей имеющих эти буквы.
var friends: [Friend] = Friend.allFriends()
var countFirstLetter: (letter: [String], repetition: [Int]) = Friend.countFirstLetter()
var countFriends = 0
//MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view
override func numberOfSections(in tableView: UITableView) -> Int {
return countFirstLetter.letter.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countFirstLetter.repetition[section]
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return countFirstLetter.letter[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FriendCell", for: indexPath) as! FriendCell
cell.configureCell(friend: friends[indexPath.item + countFriends])
countFriends += 1
return cell
}
Не могу разобраться, как работает переопредление ячеек и почему элементы повторяются

Два вопроса:
- Как узнать, какую секцию заполняет таблица. Тогда я смогу исправить проблему на первом фото и увеличивать Count только, когда меняется секция.
- Как решить проблему с перезаполнением ячеек, чтобы в строке оставался нужный элемент
Ответы (1 шт):
indexPath в каждой секции свой, т.е. есть indexPath.section и indexPath.row (это к вопросу как узнать, какая сейчас секция заполняется), поэтому у вас indexPath.item в каждой секции начинается сначала и элементы повторяются. Можно сделать просто cell.configureCell(friend: friends[countFriends]). Хотя это не очень гибкое решение, лучше сделать массив секций, в котором будем номер секции и массив ячеек секции: [section, [rows]]:
struct Objects {
var sectionName : String
var sectionObjects : [String]
}
var objectArray = [Objects]()
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return objectArray.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectArray[section].sectionObjects.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return objectArray[section].sectionName
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row]
return cell
}
