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和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 ()
}
但现在表格还有另一个问题up,可能会出现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 :) 滚动浏览表视图直到由索引路径标识的行处于特定的lo屏幕上显示阳离子。
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)
你可以使用我的扩展
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屋!