我有一個 tableView 和 json 資料。我希望 tableview 在 json 資料中加載一半。當表格視圖滾動到前半部分結束時,另一半將被加載。有人知道我該怎么做嗎?
uj5u.com熱心網友回復:
我相信您將不得不在您到達 tableview 的末尾以加載下一批pagination的幫助下進行某種型別的處理scrollViewDidScroll
首先設定一些初始變數來幫助您跟蹤分頁程序。
var pageStart = 0
var pageSize = 15
// scrollViewDidScroll will be called several times
// so we need to be able to block the loading process
var isLoadingItems = false
// Array of 50 values which you get from the API
// For example your JSON data
var totalNumberOfItems = (0...49).reduce([Int]())
{ (result, number) in
var array = result
array.append(number)
return array
}
// This will periodically be filled with items from totalNumberOfItems
var itemsToLoad: [Int] = []
我創建了這個加載函式,它有助于批量添加專案并適當地重新加載 tableview
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
loadItems()
}
private func loadItems(withDelay delay: Double = 0) {
// Check that there are items to load
if pageStart < totalNumberOfItems.count, !isLoadingItems {
isLoadingItems = true
// The delay and dispatch queue is just to show you the
// loading of data in batches, it is not needed for the
// solution
if delay > 0 {
presentLoader()
}
DispatchQueue.main.asyncAfter(deadline: .now() delay) {
if delay > 0 {
// dismiss the loader
self.dismiss(animated: true, completion: nil)
}
// Calculate the page end based on the page size or on
// the number of items remaining to load if the page size
// is greater than the number of items remaining
var pageEnd = self.pageStart self.pageSize - 1
if pageEnd > self.totalNumberOfItems.count {
let remainingItems = self.totalNumberOfItems.count - self.pageStart - 1
pageEnd = self.pageStart remainingItems
}
let newItems = Array(self.totalNumberOfItems[self.pageStart ... pageEnd])
self.itemsToLoad.append(contentsOf: newItems)
self.pageStart = pageEnd 1
let indexPaths = newItems.map { IndexPath(row: $0,
section: 0) }
// Update the table view
self.tableView.beginUpdates()
self.tableView.insertRows(at: indexPaths, with: .fade)
self.tableView.endUpdates()
// scroll to first newly inserted row
if let firstNewRow = indexPaths.first {
self.tableView.scrollToRow(at: firstNewRow,
at: .top,
animated: true)
}
// Unlock the loading process
self.isLoadingItems = false
}
}
}
然后觀察您是否使用scrollViewDidScroll并重新加載表格視圖以顯示插入的行
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Check that the current scroll offset is > 0 so you don't get
// any false positives when the table view is set up
// and check if the current offset has reached the end
if scrollView.contentOffset.y >= 0 &&
scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
print("reached end, load more")
// Load more data
loadItems(withDelay: 1)
}
}
下面是它的外觀:

如果您發現某些部分難以遵循或添加到您自己的代碼中,可以在此處找到可以按原樣運行的完整代碼:
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447628.html
