再谈iOS15后的Pull-To-Refresh


6个月前 293次点击 来自 移动端

标签: SwiftUI

原文链接:
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)
    }
}

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑