【SwiftUI】ListとForEarch
今回は、SwiftUIのListとForEarchについて記載していきます。
・ListとForeach基本的な使い方
ListとForeach基本的な使い方については
下記のカビ通信サイトの方の記事が詳しいのでご参照ください。
・【SwiftUI】Listの使い方
・【SwiftUI】ForEachの使い方(1/2)
・【SwiftUI】ForEachの使い方(2/2)
記事を拝見して、利用方法としては以下のコードが利用しやすいと
思いました。
・コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Fruit: Identifiable { | |
var id = UUID() | |
var name: String | |
} | |
struct ContentView: View { | |
let fruits = [ | |
Fruit(name: "peach"), | |
Fruit(name: "grape"), | |
Fruit(name: "apple") | |
] | |
var body: some View { | |
Form { | |
ForEach(fruits) { fruit in | |
Text(fruit.name) | |
} | |
} | |
} | |
} |
・スクリーンショット
・ListでHashableを利用する場合
Hashableについては下記になります。表示する対象がhashなので、ID指定をしなくても良いですね。予め一意のデータしかない場合は、こちらの実装方法でも良いですね〜。
・コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Fruit: Hashable { | |
var name: String | |
} | |
struct ContentView: View { | |
let fruits = [ | |
Fruit(name: "peach"), | |
Fruit(name: "grape"), | |
Fruit(name: "apple"), | |
] | |
var body: some View { | |
Form{ | |
ForEach(fruits, id: \.hashValue) { fruit in | |
Text(fruit.name).font(.title) | |
} | |
} | |
} | |
} |
・スクリーンショット
スクリーンショットは、表示は、ひとつ前のIdentifiableを利用時と同じです。
・ListでEnumで表現する場合
enumを利用した例は下記になります。allCasesを利用するために、CaseIterableプロトコルを利用して、rawValueが一意として、Identifiableプロトコルを利用しております。
・コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ContentView: View { | |
enum Fruit: String, CaseIterable, Identifiable { | |
case peach = "peach" | |
case grape = "grape" | |
case apple = "apple" | |
var id: String { rawValue } | |
} | |
var body: some View { | |
List { | |
ForEach(Fruit.allCases) { number in | |
Text(number.rawValue) // number.idで同じ結果 | |
} | |
} | |
} | |
} |
・スクリーンショット
スクリーンショットは、表示は、ひとつ前のIdentifiableを利用時と同じです。
・ListでForeachで複数行の更新を行う場合
1行ずつ更新するのではなく、複数の行を更新させることもできます。@tsuzuki817
さんのQiita記載に記載にありますので,
以下をご参照ください。
・【SwiftUI】ListとForEachの挙動について...