UITableview Scrolls to Top on Reload
Я сталкиваюсь с проблемой в своем приложении - вы можете публиковать и редактировать свои любимые места. После публикации сообщения или редактирования определенного сообщения (UITableViewCell
) перезагружается UITableview
.
Моя проблема: UITableview
прокручивается вверх после перезагрузки. Но это не то, что я хочу. Я хочу, чтобы мое мнение оставалось в камере/в представлении, где я был. Но я не знаю, как это сделать.
Не могли бы вы мне помочь?
Ответы
Ответ 1
Метод UITableView
reloadData()
явно является принудительной перезагрузкой всего tableView. Он работает хорошо, но, как правило, раздражает и плохой пользовательский интерфейс, если вы собираетесь делать это с помощью таблицы, которую пользователь в настоящее время ищет.
Вместо этого взгляните на reloadRowsAtIndexPaths(_:withRowAnimation:)
и
reloadSections(_:withRowAnimation:)
в документации.
Ответ 2
Ответ Игоря правильный, если вы используете динамически изменяемые ячейки (UITableViewAutomaticDimension)
Здесь он находится в быстрой 3:
private var cellHeights: [IndexPath: CGFloat?] = [:]
var expandedIndexPaths: [IndexPath] = []
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellHeights[indexPath] = cell.frame.height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = cellHeights[indexPath] {
return height ?? UITableViewAutomaticDimension
}
return UITableViewAutomaticDimension
}
func expandCell(cell: UITableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
if !expandedIndexPaths.contains(indexPath) {
expandedIndexPaths.append(indexPath)
cellHeights[indexPath] = nil
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
//tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
}
Ответ 3
Чтобы предотвратить прокрутку вверх, вы должны сохранять высоты ячеек при их загрузке и давать точное значение в tableView:estimatedHeightForRowAtIndexPath
:
// declare cellHeightsDictionary
NSMutableDictionary *cellHeightsDictionary;
// initialize it in ViewDidLoad or other place
cellHeightsDictionary = @{}.mutableCopy;
// save height
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath];
}
// give exact height value
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSNumber *height = [cellHeightsDictionary objectForKey:indexPath];
if (height) return height.doubleValue;
return UITableViewAutomaticDimension;
}
Ответ 4
В быстрой версии 3.1
DispatchQueue.main.async(execute: {
self.TableView.reloadData()
self.TableView.contentOffset = .zero
})
Ответ 5
Просто пойдите для этих строк, если вы хотите простое решение
let contentOffset = tableView.contentOffset
tableView.reloadData()
tableView.setContentOffset(contentOffset, animated: false)