pull-to-refresh

1个月前 96次点击 来自 iOS

原文地址:How to enable pull to refresh

在APP开发中,Pull To Refresh下拉刷新组件是目前最常用的数据刷新方式,在SwiftUI中并没有相关组件,可使用开源组件替换一部分使用场景:https://github.com/AppPear/SwiftUI-PullToRefresh
不过在iOS15之后,系统内部将通过refreshable() modifier来实现这一功能:

struct NewsItem: Decodable, Identifiable {
    let id: Int
    let title: String
    let strap: String
}

struct ContentView: View {
    @State private var news = [
        NewsItem(id: 0, title: "Want the latest news?", strap: "Pull to refresh!")
    ]

    var body: some View {
        NavigationView {
            List(news) { item in
                VStack(alignment: .leading) {
                    Text(item.title)
                        .font(.headline)
                    Text(item.strap)
                        .foregroundColor(.secondary)
                }
            }
            .refreshable {
                do {
                    // Fetch and decode JSON into news items

                    let url = URL(string: "https://www.hackingwithswift.com/samples/news-1.json")!
                    let (data, _) = try await URLSession.shared.data(from: url)
                    news = try JSONDecoder().decode([NewsItem].self, from: data)
                } catch {
                    // Something went wrong; clear the news
                    news = []
                }
            }
        }
    }
}

查阅上面代码,在refreshable发起了异步(强烈建议食用:Swift 5.5 新属性 async/await)网络请求。

Card image cap
开发者雷

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

要加油~~~

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