UITableView Refresh without scrolling

后端 未结 12 753
时光说笑
时光说笑 2021-02-03 23:06

I have a _TableView with items , and I want to set automatic refresh,and I don\'t want it to scroll on refresh , lets say user scrolled 2 pages down , and the refre

12条回答
  •  眼角桃花
    2021-02-03 23:22

    i wrote something that works perfect for me:

    extension UIScrollView {
        func reloadDataAndKeepContentOffsetInPlace(reloadData:(() -> Void)) {
        let currentContentHeight = contentSize.height
        if currentContentHeight == .zero {
           reloadData()
           return
        }
        reloadData()
        layoutIfNeeded()
        let newContentHeight = self.contentSize.height
        DispatchQueue.main.async {
            var contentOffset = self.contentOffset
            contentOffset.y += newContentHeight - currentContentHeight
            self.setContentOffset(contentOffset, animated: false)
        }
      }
    }
    

    use like this:

       self.reloadSomeData()
       collectionView.reloadDataAndKeepContentOffsetInPlace { [weak self] in
                                    guard let self = self else { return }
                                    self.collectionView.reloadData()
                                }
    

提交回复
热议问题