UITableView Refresh without scrolling

2020-05-25 03:49发布

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 refresh trigered -> so I want to put the refreshed content to the top of the table without interupting user's scrolling

Assume user was on row 18 and now the _dataSource is refreshed so it fetched lets say 4 items , so I want user to stay on the item he was.

What would be the best approach to achieve it ??

11条回答
倾城 Initia
2楼-- · 2020-05-25 04:14

Swift 4.2 : Simple Solution

override func viewDidLoad() {
 super.viewDidLoad()

 self.tableView.estimatedRowHeight = 0
 self.tableView.estimatedSectionHeaderHeight = 0
 self.tableView.estimatedSectionFooterHeight = 0
}

//And then simply update(insert, reloadSections, delete etc) your tableView or reload

tableView.reloadData()

//or

UIView.performWithoutAnimation {

  tableView.beginUpdates()
  .....
  tableView.endUpdates()
}
查看更多
Explosion°爆炸
3楼-- · 2020-05-25 04:15

Use Extension

create UITableViewExtensions.swift and add following:

extension UITableView {

    func reloadDataWithoutScroll() {
        let offset = contentOffset
        reloadData()
        layoutIfNeeded()
        setContentOffset(offset, animated: false)
    }
}
查看更多
走好不送
4楼-- · 2020-05-25 04:18

SWIFT 3

let contentOffset = self.tableView.contentOffset
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
self.tableView.setContentOffset(contentOffset, animated: false)

This is error of iOS8 when using UITableViewAutomatic Dimension. We need store the content offset of table, reload table, force layout and set contenOffset back.

CGPoint contentOffset = self.tableView.contentOffset;
[self.tableView reloadData];
[self.tableView layoutIfNeeded];
[self.tableView setContentOffset:contentOffset];
查看更多
ゆ 、 Hurt°
5楼-- · 2020-05-25 04:19

This code will prevent unnecessary animation and maintain the scroll view's content offset, it worked fine for me.

let lastScrollOffset = tableView.contentOffset
tableView.beginUpdates()
tableView.reloadData()
tableView.endUpdates()
tableView.layer.removeAllAnimations()
tableView.setContentOffset(lastScrollOffset, animated: false)
查看更多
别忘想泡老子
6楼-- · 2020-05-25 04:19

In iOS 12.x, using Xcode 10.2.1, an easier option is.

UIView.performWithoutAnimation { 
    let loc = tableView.contentOffset
    tableView.reloadRows(at: [indexPath], with: .none)
    tableView.contentOffset = loc
}

This works better than following; it shakes at times when the row is not fully visible.

let contentOffset = self.tableView.contentOffset
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
self.tableView.setContentOffset(contentOffset, animated: false)
查看更多
登录 后发表回答