再谈iOS15后的Pull-To-Refresh

1个月前 60次点击 来自 iOS

原文链接:
Pull to refresh in SwiftUI with refreshable

之前的博客中已经讲述了iOS15后.refreshable的使用方法:

struct ContentView: View {
    @State var data = Array(0..<10)

    var body: some View {
        List {
            ForEach(data, id: \.self) { i in
                Text(i.description)
            }
        }
        .refreshable {
          await loadMore() // 1
        }
    }
    
    func loadMore() async { 
        let request = URLRequest(url: URL(string: "https://httpbin.org/delay/2")!) // 2
        let _ = try! await URLSession.shared.data(for: request)
        data.append(contentsOf: Array(10..<20)) // 3
    }
}

前天刷到上文的博客,进一步提高了对它的认识,下面是使用.refreshable对控件自定义添加刷新,具体构建过程请跳转原文:

1. 自定义控件Refresher

struct Refresher: View {
    @Environment(\.refresh) private var refresh
    @State private var isLoading = false // 1

    var body: some View {
        VStack {
            Text("Refresher")
            if let refresh = refresh {
                if isLoading { // 2
                    ProgressView()
                } else {
                    Button("Refresh") {
                        isLoading = true // 3
                        async {
                            await refresh()
                            isLoading = false // 4
                        }
                    }
                }
            }
        }
    }
}

2.使用

struct ContentView: View {
    var body: some View {
        VStack {
            Refresher()
                .refreshable {
                    await loadMore() // 1
                }
            Divider()
            Refresher()
        }.padding()
    }
    
    func loadMore() async {
        let request = URLRequest(url: URL(string: "https://httpbin.org/delay/2")!)
        let _ = try! await URLSession.shared.data(for: request)
    }
}

Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识,就不会无聊了

要加油~~~

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签