SwiftUI中实现List下拉刷新
在SwiftUI中实现List的下拉刷新功能
在本篇博客中,我们将详细探讨如何在SwiftUI中为List
视图添加下拉刷新功能。这是一个常见的需求,特别是在展示动态数据列表时。我们还将通过一个实例展示如何从网络获取数据并更新列表。此外,你可以通过以下链接查看相关视频教程:
实现步骤
首先,我们需要导入必要的SwiftUI库,并定义一个ContentView
结构,其中包含列表数据和一个加载状态标志。
ContentView 结构
import SwiftUI
struct ContentView: View {
@State private var dataList: [Int] = []
@State private var isLoading: Bool = false
var body: some View {
NavigationStack {
List(dataList, id: \.self) { item in
Text("\(item)")
}
.refreshable {
fetchData()
}
.navigationTitle("Data List")
}
.onAppear {
fetchData()
}
}
}
fetchData 函数
fetchData函数是核心,用于加载数据。首先检查isLoading标志以避免重复加载。然后尝试从给定URL获取数据,解析数据,并更新列表。
func fetchData() {
if (isLoading) {
return
}
isLoading = true
guard let url = URL(string: "https://vae.life/V240423/random") else {
print("Invalid URL")
isLoading = false
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else {
print("No data in response: \(error?.localizedDescription ?? "Unknown error")")
isLoading = false
return
}
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
dataList = decodedResponse.data
isLoading = false
}
} else {
print("Failed to decode response")
isLoading = false
}
}.resume()
}
Response 结构
为了方便地解析JSON响应,我们定义了一个符合Codable协议的Response结构体。
struct Response: Codable {
let code: Int
let data: [Int]
}
完整源码
import SwiftUI
struct ContentView: View {
@State private var dataList: [Int] = []
@State private var isLoading: Bool = false
var body: some View {
NavigationStack {
List(dataList, id: \.self) { item in
Text("\(item)")
}
.refreshable {
fetchData()
}
.navigationTitle("Data List")
}
.onAppear {
fetchData()
}
}
func fetchData() {
if (isLoading) {
return
}
isLoading = true
guard let url = URL(string: "https://vae.life/V240423/random") else {
print("Invalid URL")
isLoading = false
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else {
print("No data in response: \(error?.localizedDescription ?? "Unknown error")")
isLoading = false
return
}
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
dataList = decodedResponse.data
isLoading = false
}
} else {
print("Failed to decode response")
isLoading = false
}
}.resume()
}
}
struct Response: Codable {
let code: Int
let data: [Int]
}
#Preview {
ContentView()
}
总结
通过上述代码,我们展示了如何在SwiftUI应用中为列表添加下拉刷新功能,以及如何处理网络请求和更新UI。这为开发具有动态数据交互的现代应用提供了基础。
希望你能从这篇教程中获得帮助,并成功实现你的项目需求!
License:
CC BY 4.0