iOS TableView 重新加载并滚动顶部 [英] iOS TableView reload and scroll top
问题描述
第二天我无法解决表的问题.
the second day I can not solve the problem with the table.
我们有一个 segmentedControl,它在改变时会改变表格.假设控件的段中有 3 个元素,相应地有 3 个数组(这很重要,它们的大小不同)当 segmentedControl 改变时,我需要向上滚动表格.
We have a segmentedControl which, when changed, changes the table. Suppose that there are 3 elements in the segment of the control and, correspondingly, 3 arrays (which is important, they are of different sizes) I need to scroll table up when segmentedControl is changed.
看起来一切都很简单:contentOffset = .zero and reloadData()
And it seems like everything is simple: contentOffset = .zero and reloadData ()
但是.这不起作用,我不知道为什么表格没有向上滚动.
But. This does not work, I do not know why the table not scroll up.
唯一有效的方法:
UIView.animate (withDuration: 0.1, animations: {
self.tableView.contentOffset = .zero
}) {(_) in
self.tableView.reloadData ()
}
但是现在表上升的时候又出现了一个问题,可能会出现bug,因为segmentedControl发生了变化,其他数组中的数据可能没有,我们还没有做reloadData()
But now there is another problem when the table goes up, a bug may occur, because the segmentedControl has changed, and the data in the other array may not be, we have not yet done reloadData ()
也许我无法理解显而易见的事情))祝贺即将到来的假期!
Maybe I can not understand the obvious things)) Congrats on the upcoming holidays!
推荐答案
UItableView
方法 scrollToRow(at:at:animated:) 滚动表格视图,直到由索引路径标识的行位于屏幕上的特定位置.
UItableView
method scrollToRow(at:at:animated:) Scrolls through the table view until a row identified by index path is at a particular location on the screen.
使用
tableView.scroll(to: .top, animated: true)
你可以使用我的扩展程序
You can use my extension
extension UITableView {
public func reloadData(_ completion: @escaping ()->()) {
UIView.animate(withDuration: 0, animations: {
self.reloadData()
}, completion:{ _ in
completion()
})
}
func scroll(to: scrollsTo, animated: Bool) {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
let numberOfSections = self.numberOfSections
let numberOfRows = self.numberOfRows(inSection: numberOfSections-1)
switch to{
case .top:
if numberOfRows > 0 {
let indexPath = IndexPath(row: 0, section: 0)
self.scrollToRow(at: indexPath, at: .top, animated: animated)
}
break
case .bottom:
if numberOfRows > 0 {
let indexPath = IndexPath(row: numberOfRows-1, section: (numberOfSections-1))
self.scrollToRow(at: indexPath, at: .bottom, animated: animated)
}
break
}
}
}
enum scrollsTo {
case top,bottom
}
}
这篇关于iOS TableView 重新加载并滚动顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!