SwiftUIでデータを一覧表示したい場合にはListを使用します。
配列と組み合わせて使用する場合が多いのですが、データを一つずつ指定して表示することもできます。 テキストだけでなく、複数のコントロールを組み合わせて表示することができるため、データを表示するだけでなく、入力用の画面でも使用されます。
以下具体的な手順を説明します。
最もシンプルなList
最も基本的な使い方です。Listの中身が順番に表示されます。
struct ListStatic: View {
var body: some View {
List {
Text("田中")
Text("佐藤")
Text("山田")
}
}
}
実行結果です。

Listの中身はTextに限らず、Buttonなど自由に設定できます。
配列を表示するList
配列の内容をListとして表示することもできます。
struct ListArray: View {
let persons = ["田中", "佐藤", "山田"]
var body: some View {
List {
ForEach(persons, id: \.self) { person in
Text(person)
}
}
}
}
実行結果です。

実際のアプリでは配列の内容をプログラムから変更し、その内容をListとして表示する事が多いと思います。
Sectionでグループ化する
Sectionを使用してグループ化することもできます。各グループにはヘッダーを追加できます。
struct ListSection: View {
var body: some View {
List {
Section {
Text("田中")
Text("山田")
} header: {
Text("人間")
}
Section {
Text("リンゴ")
Text("バナナ")
} header: {
Text("くだもの")
}
}
}
}
実行結果です。

スタイルの指定
.listStyleモディファイアを使用して、Listのスタイルを指定することができます。
List {
(省略)
}
//デフォルトのスタイル
.listStyle(DefaultListStyle())
//プレインスタイル
.listStyle(.plain)
//グループ化されたスタイル
.listStyle(.grouped)
//マージンがあるスタイル
.listStyle(.inset)
//マージンとグループ
.listStyle(.insetGrouped)
//サイドバー
.listStyle(.sidebar)
.default

.plain

.grouped

.inset

.insetGrouped

.sidebar
