簡體   English   中英

UICollection 視圖的無限滾動

[英]infinite scroll for UICollection view

我試圖在我的應用程序中無限滾動,我正在從 API 調用數據,至少它在某種程度上有效,但是當我在集合視圖中滾動時,它開始在下面填充並剪切那些在頂部,所以我無法向上滾動到它們,然后在填充后它只是跳過並超出范圍,這里有一些代碼請幫忙。

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()
 }

現在可以了,我所要做的就是刪除該行

self.productSearchResults = [Products]()

沒必要

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM