我在我的ViewController中添加了一个UICollectionView作为子视图。我还为UICollectionView设置了一个UIRefreshControl,当我下拉刷新时,它会应用一个NSDiffableDataSourceSnapshot。应用快照时,动画会跳转(请注意,即使导航栏标题不大,也会发生这种情况)。

下面是相关的代码片段
var collectionView: UICollectionView! = nil
var dataSource: UICollectionViewDiffableDataSource<Section, Item>! = nil
override func viewDidLoad() {
super.viewDidLoad()
let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout:
generateLayout())
view.addSubview(collectionView)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = .systemGroupedBackground
self.collectionView = collectionView
collectionView.delegate = self
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)
collectionView.refreshControl = refreshControl
}
@objc func doSomething(refreshControl: UIRefreshControl) {
DispatchQueue.main.async {
var dataSourceSnapshot = NSDiffableDataSourceSnapshot<Section, Item>()
// add data
dataSource.apply(dataSourceSnapshot)
}
refreshControl.endRefreshing()
}是否可以进行任何更改以应用快照而不会突然跳转?
发布于 2021-03-20 12:04:25
不幸的是,从iOS 6开始,苹果工程师就不能很好地解决这个问题。
长话短说:你不想在滚动视图isTracking的时候使用endRefreshing。UIRefreshControl修改了scrollView的contentInset和contentOffset,它总是引起这样的跳跃。
如果您有一个网络请求状态,或者任何其他指示加载正在进行的标志,您可以简单地执行以下操作:
@objc func doSomething(refreshControl: UIRefreshControl) {
loading = true
DispatchQueue.main.async {
var dataSourceSnapshot = NSDiffableDataSourceSnapshot<Section, Item>()
// add data
dataSourceSnapshot.appendSections([.test])
dataSourceSnapshot.appendItems([.test])
self.dataSource.apply(dataSourceSnapshot)
self.loading = false
}
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !loading && collectionView.refreshControl!.isRefreshing {
collectionView.refreshControl!.endRefreshing()
}
}我不太喜欢这样的loading标志,但这只是一个例子。希望你有更好的真相来源,表明一些“工作”是否仍在进行中。
我猜可能有一个更好的方法来解决这个问题(通过在运行时修补类),但它通常需要时间来研究。我想知道这个解决方案是否能满足您的需求。
https://stackoverflow.com/questions/66626029
复制相似问题