У меня есть расширяемый UITableView
.Когда разделы касаются, они раскрываются или сворачиваются с анимацией (прокрутка).Моя проблема в том, что при расширении или свертывании заголовков возникает странная анимация.UITableView
прокручивается к вершине и затем идет к повернутой ячейке.Кроме того, когда нет расширенной ячейки, иногда она не прокручивается вверх, и между верхним заголовком и видом сверху UITableView
имеется большое пространство.
Моя проблема в том, что мне нужно прокрутить до расширенного раздела, а также избавиться от ошибки прокрутки до верха.
Я пробовал приведенное ниже решение, но у меня не получилось: предотвратить таблицувид сверху прокрутки после insertRows
Это также похоже на ту же проблему с вопросом ниже, но не может понять, как это реализовать. Почему мой UITableView «прыгает» при вставке или удалении строки?
Как переключать выбор:
func toggleSection(header: DistrictTableViewHeader, section: Int) {
print("Trying to expand and close section...")
// Close the section first by deleting the rows
var indexPaths = [IndexPath]()
for row in self.cities[section].districts.indices {
print(0, row)
let indexPath = IndexPath(row: row, section: section)
indexPaths.append(indexPath)
}
let isExpanded = self.cities[section].isExpanded
if(isExpanded){
AnalyticsManager.instance.logPageEvent(screenName: analyticsName!, category: "Button", action: Actions.interaction, label: "\(self.cities[section].name) Collapse Click")
}else{
AnalyticsManager.instance.logPageEvent(screenName: analyticsName!, category: "Button", action: Actions.interaction, label: "\(self.cities[section].name) Expand Click")
}
self.cities[section].isExpanded = !isExpanded
// This call opens CATransaction context
CATransaction.begin()
// This call begins tableView updates (not really needed if you only make one insertion call, or one deletion call, but in this example we do both)
tableView.beginUpdates()
if isExpanded {
tableView.deleteRows(at: indexPaths, with: .automatic)
} else {
tableView.insertRows(at: indexPaths, with: .automatic)
}
// completionBlock will be called after rows insertion/deletion animation is done
CATransaction.setCompletionBlock({
// This call will scroll tableView to the top of the 'section' ('section' should have value of the folded/unfolded section's index)
if !isExpanded{
self.tableView.scrollToRow(at: IndexPath(row: NSNotFound, section: section) /* you can pass NSNotFound to scroll to the top of the section even if that section has 0 rows */, at: .top, animated: true)
}
})
if self.scrollToTop(){
self.tableView.setContentOffset(.zero, animated: true)
}
// End table view updates
tableView.endUpdates()
// Close CATransaction context
CATransaction.commit()
}
private func scrollToTop() -> Bool{
for sec in self.cities{
if(sec.isExpanded){
return false
}
}
return true
}
Iдаю высоту ячейки внутри;
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
Как я объявляю заголовки;
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = DistrictTableViewHeader()
header.isColapsed = !self.cities[section].isExpanded
header.customInit(title: self.cities[section].name, section: section, delegate: self)
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
РЕДАКТИРОВАТЬ: Решение вэтот вопрос (установка приблизительной высоты в 0) выглядит как работающий при вставке строки.Тем не менее, у меня все еще есть ошибка при удалении строк.Нижний заголовок переходит в центр табличного представления, а затем - после заголовка свертывания.
iOS 11 Плавающий заголовок TableView