![見出し画像](https://assets.st-note.com/production/uploads/images/68227939/rectangle_large_type_2_c0037cd08e96845f5ea3e0a0dc28d830.png?width=1200)
SwiftUIでいこう! -Pull to Refresh(new!)
2021のWWDCで発表されてOS 15がリリースされています。今使えるようになっています。以下サイトで紹介されているものを参考にコードを実行していき気になったことを書き留めておきたいと思います。
まずは画面を引っ張って、離す(Pull To Refresh)と更新されるという機能の実装です。
モディファイアを使って簡単に実装することができるようになりました。
公式サイトは
簡単実装です。
struct ContentView: View {
var body: some View {
NavigationView {
List(1..<100) { row in
Text("Row \(row)")
}
.refreshable {
print("Do your refresh work here")
}
}
}
}
日本語で解説してあるサイトは以下。
そのモディファイアですが、
.refreshable {
print("Do your refresh work here")
}
{ }の中に実行する命令を書いて実行してみます。プレビューもしくはシュミレータで画面を引っ張って更新、Pull To Refreshすると、コンソールに
"Do your refresh work here"
と出ます。
リスト表示の画面にJsonファイルの読みができるような処理は以下のようになります。
まず、jsonファイルを読み込めるようにcodableで定義します。
struct NewsItem: Decodable, Identifiable {
let id: Int
let title: String
let strap: String
}
これを使ってリストに表記できるようにコードを書いていきます。
リストの内容ですが初期の文字のみ入っています。これを更新させます。 @Stateで更新ができるようにしています。
@State private var news = [
NewsItem(id: 0, title: "Want the latest news?", strap: "Pull to refresh!")
]
実際の画面のレイアウトを作っていきます。
var body: some View {}
に処理を書きます。リスト部分から。
List(news) { item in
VStack(alignment: .leading) {
Text(item.title)
.font(.headline)
Text(item.strap)
.foregroundColor(.secondary)
}
}
あとはモディファイアの部分です。
.refreshable {
do {
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 = []
}
}
全体です。
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 = []
}
}
}
}
}