对于何时加载新对象的方法,这是我的实现
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex {
// print("this is the last cell")
if (!isMoreDataLoading) { //is not loading more
// start loading indicator
loadMoreFeed()
// Update position of loadingMoreView, and
loadingMoreView?.frame = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: InfiniteScrollActivityView.defaultHeight)
loadingMoreView!.startAnimating()
self.tableView.tableFooterView = loadingMoreView
self.tableView.tableFooterView?.isHidden = false
}
}
}
为了更新tableView,这是我的实现
private func updateTableView() {
let rowsBefore = self.tableObjects.count
loadMoreFeedInBackground() { queryObjects in
for object in queryObjects! {
self.tableObjects.append(object)
}
self.tableObjects.sort {
$0.date!.compare($1.date!) == .orderedDescending
}
let rowsAfter = self.tableObjects.count
let indexes = rowsAfter - rowsBefore
guard indexes > 0 else {
self.isMoreDataLoading = false
self.loadingMoreView!.stopAnimating()
self.tableView.tableFooterView?.isHidden = true
return
}
var indexPaths = [IndexPath]()
for index in 0...(indexes - 1) {
let indexPath = IndexPath(row: index + rowsBefore, section: 0)
indexPaths.append(indexPath)
}
if tableView.contentOffset.y > tableView.estimatedRowHeight {
let initialOffset = self.tableView.contentOffset
tableView.beginUpdates()
tableView.insertRows(at: indexPaths, with: .fade)
tableView.setContentOffset(initialOffset, animated: false)
tableView.endUpdates()
} else {
tableView.insertRows(at: indexPaths, with: .fade)
}
//refreshControl.endRefreshing()
}