16
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【SwiftUI】ListとForEachの挙動について...

Last updated at Posted at 2019-11-06

はじめに

※これは個人的なイメージです:thinking:
あんまりわかっていないので、指摘、助言、批評など絶賛募集中です!

問題

以下のように実装した場合

struct ContentView: View {
    var body: some View {
        List(0..<3) {(row: Int) in
            Text("Row \(row)")
                .listRowBackground(Color.blue)
        }
    }
}

スクリーンショット 2019-11-06 23.09.32.png
ご覧の通り、.listRowBackground(Color.blue)がListのcellに反映されていません:sob:

List + ForEachで対応した場合

struct ContentView: View {
    var body: some View {
        List {
            ForEach(0..<3) {(row: Int) in
                Text("Row \(row)")
                    .listRowBackground(Color.blue)
            }
        }
    }
}

スクリーンショット 2019-11-06 23.12.02.png
ちゃんと.listRowBackground(Color.blue)が効いている!
何故なのか?:confounded:

別例:rolling_eyes:

 このように実装した場合

struct ContentView: View {
    var body: some View {
        List (0..<3) {(row: Int) in
            Text("Row \(row)")
            Spacer()
            Text("hoge")
        }
    }
}

以下のように表示されます。
スクリーンショット 2019-11-06 23.20.14.png

つまり、Listのみの場合TableViewの1行の中のViewとして扱われているイメージ!
名称未設定アートワーク 2.png

一方、ForEachと組み合わせた場合

struct ContentView: View {
    var body: some View {
        List {
            ForEach(0..<3) {(row: Int) in
                Text("Row \(row)")
                Spacer()
                Text("hoge")
            }
        }
    }
}

以下のように表示されます。

スクリーンショット 2019-11-06 23.19.13.png

これは、下図のようにclosureから複数のViewを作成しているためだと思われます。
名称未設定アートワーク 1.png

最終的な着地点

  • Listは1つのカラムを返す
  • ListとForEachを組み合わせることで、動的にViewを提供することができるようになる
    名称未設定アートワーク.png

 参考URL

16
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?