gpt4 book ai didi

ios - UICollectionview 的无限滚动

转载 作者:行者123 更新时间:2023-11-28 07:20:58 25 4
gpt4 key购买 nike

我试图在我的应用程序中无限滚动,我正在从 API 调用数据,至少它在某种程度上有效,但是当我在 Collection View 中滚动时,它开始在下方填充并剪切上面的那些,所以我无法向上滚动到它们,然后在填充它之后只是跳过并超出范围,这里有一些代码请帮忙。

var fetchMore = false
var pageNumber = 0

var productPageString: String {
if pageNumber == 0 {
return "pageNumber=0&"
} else {
return "pageNumber=\(pageNumber)&"
}
}

func fetchProducts() {
fetchMore = false
let validatedTextString = UserDefaults.standard.object(forKey: "productsSearchValue")
let searchText = validatedTextString!
let urlString = APIConstants.baseurl + APIConstants.products + "?searchString=\(searchText)&\(productPageString)itemsPerPage=20"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
let jsonData = try JSONDecoder().decode(ProductSearch.self, from: data!)

self.productSearchResults = [Products]()

for dictionary in jsonData.data {
let product = Products(productId: dictionary.productId, categoryId: dictionary.categoryId, storeId: dictionary.storeId, name: dictionary.name, description: dictionary.description, imageUrl: dictionary.imageUrl, price: dictionary.price)
self.productSearchResults?.append(product)
self.fetchMore = true
}

} catch let jsonError {
print(jsonError)
}
}.resume()
}

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height

if offsetY > contentHeight - scrollView.frame.height {
if fetchMore {
fetchProducts()
pageNumber += 1
}
}
}

它最初显示每页 20 个项目,但随着页码的增加,它会不断填充该特定页面中的其他内容,但我仍然只能查看每页 20 个项目。我希望能够向上滚动到之前的内容,而且,为什么它最终会自动将我带到最后?谢谢

最佳答案

你需要重新加载

 for dictionary in jsonData.data {
let product = Products(productId: dictionary.productId, categoryId: dictionary.categoryId, storeId: dictionary.storeId, name: dictionary.name, description: dictionary.description, imageUrl: dictionary.imageUrl, price: dictionary.price)
self.productSearchResults?.append(product)
}

self.fetchMore = true

DispatchQueue.main.async {
self.collectionView.reloadData()
}

关于ios - UICollectionview 的无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58087048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com