
ListでViewを表示すると、デフォルトで隙間ができたりして、めたくそムカついたので、調べたら解決方法がちゃんとあったので、メモしておきます。
Listの隙間1:Listの形状による隙間
Listをデフォルトで設定すると、Listの形状、つまりListはめいいっぱい左右に広がってるわけではなくて、真ん中にListのエリアが設置されて、縦に並んでいます。
今回は、この背景の薄いグレーの部分を消し去ります。
Listのクロージャに .listStyle(GroupedListStyle()) をつければ、Listの形が変わってなくなるらしい
コード
struct test_listinsets: View {
var body: some View {
List{
listItem()
listItem()
listItem()
}
.listStyle(GroupedListStyle()) ///←この行を追加した
}
}
struct listItem:View{
var body: some View{
Rectangle()
.frame(maxWidth: .infinity)
.frame(height:200)
.foregroundColor(Color.green)
}
}
結果
Listの隙間2:Listエリア内のViewの左右の隙間
Listのエリアを左右に広げたけれど、私がやりたかったのはListの中のViewが左右にひろがってほしいのです…。
この Listの中の配置の設定は、中のViewに
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
みたいな感じで数値で設定ができるらしいので、設定してみます
コード
struct test_listinsets: View {
var body: some View {
List{
listItem()
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) //←追加
listItem()
listItem()
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) //←追加
}
.listStyle(GroupedListStyle())
}
}
struct listItem:View{
var body: some View{
Rectangle()
.frame(maxWidth: .infinity)
.frame(height:200)
.foregroundColor(Color.green)
}
}
変化を見るために、3つのViewのうち、1、3番めのViewに適用してみました。
結果
たまにこれを使う時があって、毎度調べ直していたので今回は記録しておくことにした。
よかったよかった。デフォルトの設定関係って色々悩みますね