本文介绍了滚动到底部时 TableView 加载更多单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个 tableView,当用户滚动到最后一个单元格时,将加载更多数据.在 willDisplayCell 中,我实现了这段代码,引用自堆栈溢出中的类似问题.但是当我滚动到底部时,它不是一次加载数据,而是创建一个循环并多次调用 loadMore 函数.
I created a tableView and when user scroll to the last cell more data will be loaded. In willDisplayCell I implemented this code, referenced from similar questions in stack overflow. But when I scroll to the bottom, it is not loading data once, it creates a loop and calls loadMore function more than once.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastData = self.data!.count - 1
if indexPath.row == lastData {
currentPage += 1
self.loadData(currentPage)
}
}
func loadData() {
self.showLoadingView()
apiCALL(callback: { data
self.jsonDATA.append(contentsOf: data)
self.tableView.reloadData()
})
}
推荐答案
添加布尔参数以避免无限循环.
Add a boolean parameter to avoid infinite loop.
var isLoading = false
func loadData() {
isLoading = true
self.showLoadingView()
apiCALL(callback: { data
self.isLoading = false
self.jsonDATA.append(contentsOf: data)
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastData = self.data!.count - 1
if !isLoading && indexPath.row == lastData {
currentPage += 1
self.loadData()
}
}
这篇关于滚动到底部时 TableView 加载更多单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!