提问人:Wilson Agene 提问时间:11/14/2023 更新时间:11/14/2023 访问量:86
分页和无限滚动功能
Pagination & infinity scroll function
问:
我想写一个分页函数,让我可以无限滚动,但我发现这很困难 下面是我的 API 调用的代码:
class CoinDataService: ObservableObject {
@Published var allCoins: [CoinModel] = []
@Published var isLoading: Bool = false
var coinSubcription: AnyCancellable?
var coinListFull = false
var currentpage = 0
let perpage = 200
var canLoadMorePages = true
init() {
getCoins()
}
public func getCoins() {
guard !isLoading && canLoadMorePages else {
return
}
isLoading = true
guard let url = URL(string: "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=\(perpage)&page=\(currentpage)&sparkline=true&price_change_percentage=24h")
else { return }
coinSubcription = NetworkingManager.download(url: url)
.decode(type: [CoinModel].self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: NetworkingManager.handleCompletion, receiveValue: { [weak self] (returnedCoins) in
self?.allCoins = returnedCoins
self?.coinSubcription?.cancel()
if returnedCoins.count < self!.perpage {
self?.coinListFull = true
}
})
isLoading = false
}
我所需要的只是一个功能,它将允许我增加我的应用程序的页面
答:
-3赞
Ishtiaq Ahmed
11/14/2023
#1
尝试以下希望它有效。
要实现分页的无限滚动,您可以修改现有代码,以便在用户到达当前列表末尾时加载更多硬币。下面是 CoinDataService 类的修改版本:
import Combine
class CoinDataService: ObservableObject {
@Published var allCoins: [CoinModel] = []
@Published var isLoading: Bool = false
var coinSubcription: AnyCancellable?
var coinListFull = false
var currentpage = 1
let perpage = 200
var canLoadMorePages = true
init() {
getCoins()
}
public func getCoins() {
guard !isLoading && canLoadMorePages else {
return
}
isLoading = true
guard let url = URL(string: "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=\(perpage)&page=\(currentpage)&sparkline=true&price_change_percentage=24h")
else { return }
coinSubcription = NetworkingManager.download(url: url)
.decode(type: [CoinModel].self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { [weak self] completion in
NetworkingManager.handleCompletion(completion)
self?.isLoading = false
}, receiveValue: { [weak self] returnedCoins in
self?.allCoins.append(contentsOf: returnedCoins)
if returnedCoins.count < self!.perpage {
self?.coinListFull = true
}
self?.currentpage += 1
})
}
}
在此修改中,我进行了以下更改:
- 每次收到新硬币时,当前页都会递增。
- 将新硬币附加到现有的 allCoins 数组中,而不是 替换它。
- 在完成块中将 isLoading 设置为 false 以指示结束 的加载过程。
现在,当您调用 getCoins() 时,它将获取下一页硬币并将它们附加到现有列表中。您可以将它与 SwiftUI 列表或 ScrollView 结合使用,以实现无限滚动。请确保在 UI 中适当地处理加载状态。
评论