UITableView 拉取以使用 willDisplay 进行刷新和分页



这是我的第 3 天,在阅读了几乎数十个 tuts 之后,我不知道如何使用willDisplay方法在 UITableview 中实现分页。我正在尝试模仿iMessages拉取分页功能。

我下面的代码在第一次刷新时进入无限循环。

任何人都可以查看代码并建议一种修复无限加载的方法吗?

提前 Tx。

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 && !self.isLoading {
self.isLoading = true
fetchClientsMessages(page: self.currentPage, completed: {
if self.currentPage == 0 {
self.messageArray.removeAll()
}
self.messageArray.append(contentsOf: self.clientChatMessages!.messages!)
// Sort message by ID so that latest message appear at the bottom.
self.messageArray = self.messageArray.sorted(by: {$0.id! < $1.id!})
self.messagesTable.reloadData()
// Scroll to the top
self.messagesTable.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
self.lastPage = self.currentPage
self.currentPage = self.currentPage + 1
self.isLoading = false
})
}
}

首先加载 if 中的代码将运行,然后在它的回调中执行

self.messagesTable.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
self.isLoading = false

这将再次触发willDisplay,因为indexPath = 0isLoading = false=>无限加载,你想要的是稍微向下滚动表格以指示加载的数据,然后让用户向上滚动直到再次点击索引= 0

您应该将滚动和reloadData移动到fetchClientMessages方法中的最后一个

fetchClientsMessages(page: self.currentPage, completed: {
if self.currentPage == 0 {
self.messageArray.removeAll()
}
self.messageArray.append(contentsOf: self.clientChatMessages!.messages!)
// Sort message by ID so that latest message appear at the bottom.
self.messageArray = self.messageArray.sorted(by: {$0.id! < $1.id!})
self.lastPage = self.currentPage
self.currentPage = self.currentPage + 1
self.isLoading = false
self.messagesTable.reloadData()
// Scroll to the top
self.messagesTable.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
})

让我知道它是否有效。

最新更新