tukuyo's blog

へっぽこまん

スポンサーリンク

Outline Groupを作成する【SwiftUI】

この記事でできるもの

リストの中にリストを内包している感じのものが作れます.
f:id:tukuyoinfo:20210215111538g:plain:w300

実践

データモデルの実装

struct OutlineItem: Hashable, Identifiable {
    var id: Self { self }
    var value: String
    var children: [OutlineItem]?
}

リストに表示するデータの作成

let data = [OutlineItem(value: "おにぎりの具", children: childData1),
                  OutlineItem(value: "サンドウィッチの具", children: childData2),
                  OutlineItem(value: "絵の具", children: childData3)]

内包するデータも作成する.

let childData1 = [OutlineItem(value: "鮭"),
                            OutlineItem(value: "昆布"),
                            OutlineItem(value: "ツナマヨ")]
let childData2 = [OutlineItem(value: "きゅうり"),
                             OutlineItem(value: "れたす"),
                             OutlineItem(value: "とまと")]

let childData3 = [OutlineItem(value: "赤"),
                             OutlineItem(value: "青"),
                             OutlineItem(value: "黄")]

ビューに反映させる

struct ContentView: View {
    var body: some View {
        List {
            OutlineGroup(data, children: \.children) { item in
                Text(item.value)
                    .frame(height: 50)
            }
        }
    }
}

上記の書き方は簡略化できるので,以下を使用する.

struct ContentView: View {
    var body: some View {
        List (data, children: \.children) { item in
                Text(item.value)
                    .frame(height: 50)
        }
    }
}

スポンサーリンク