我正在尝试基于socket.io实现聊天表视图。目前,它在初始负载下可以正常工作。但是,当尝试向上分页时,滚动是跳动的,有人知道如何实现平稳滚动,例如Whatsapp或Messenger吗?
此功能最初用于加载前10条消息:
func handleGetMessages() {
socket?.on("getMessagesResponse") { [weak self] data,ack in
guard let strongSelf = self else { return }
guard
data.count > 0,
let dataObject = data[0] as? [String: Any]
else { return }
if let error = dataObject["message"] as? String {
strongSelf.showAlert(title: "", message: error, buttonTitle: "Got it")
} else {
let json = JSON(dataObject)
guard let messagesArray = json["messages"].array else { return }
guard let currentPage = json["currentPage"].int else { return }
guard let lastPage = json["lastPage"].int else { return }
strongSelf.currentPage = currentPage
strongSelf.lastPage = lastPage
messagesArray.forEach { messageObject in
guard let messageObject = messageObject.dictionaryObject else { return }
let message = Message(map: Map(mappingType: .fromJSON, JSON: messageObject))
strongSelf.messages.insert(message, at: 0)
}
if strongSelf.isPaginating {
strongSelf.isPaginating = false
strongSelf.chatTableView.reloadData()
} else {
strongSelf.chatTableView.reloadData()
guard strongSelf.chatTableView.numberOfRows(inSection: 0) - 1 > 0 else { return }
let lastRow = strongSelf.chatTableView.numberOfRows(inSection: 0) - 1
strongSelf.chatTableView.scrollToRow(at: IndexPath(row: lastRow, section: 0), at: .top, animated: false)
}
}
}
}
在willDisplayCell上,我执行此逻辑以找出用户是否已到达顶部或不将页面计数器增加一并获取更多消息
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 && !isPaginating && currentPage != lastPage {
currentPage += 1
isPaginating = true
getMessages()
}
}
从编写的代码中,我希望在滚动时能达到诸如whatsapp或Messenger平滑度之类的效果,但结果却是跳跃式滚动。
有关问题,请参见以下gif: