ZStackを使ってレイアウトをする上で、alignmet、background、frame等はどのように設定するのか確認してみます。
Xcode 13..14
ZStack
ZStackなどStackには他にVStack、HSTackやLazyVStack、LazyHStackがありました。
VStackはいわゆる平面的なY軸の垂直方向、HStackはX軸の水平方向ですが、
ZStackはZ軸の立体的な垂直方向になります。
複数のアイテムを設定するために、VStack、HStack、ZStackを使ってレイアウトできます。
またLazyVStack, La…
ここでは特にZStackについて細かく設定を確認します。
目次
1. alignment
1.1 topLeading
1.2 top
1.3 topTrailing
1.4 leading
1.5 center
1.6 trailing
1.7 bottomLeading
1.8 bottom
1.9 bottomTrailing
2. background
3. frame
1. alignment
1.1 topLeading
1.2 top
1.3 topTrailing
1.4 leading
1.5 center
1.6 trailing
1.7 bottomLeading
1.8 bottom
1.9 bottomTrailing
2. background
3. frame
alignment
ZStackはViewを重ねますが子Viewに対して alignment ができます。デフォルトはcenterですがその他八方向に配置が可能です。
topLeading
Circle図形と文字列のStackです。
|
1 2 3 4 5 6 7 8 |
ZStack(alignment: .topLeading){ Circle() .frame(width: 200, height: 200, alignment: .center) .foregroundColor(.orange) Text("ZStack") } |

(青い矩形枠はStackを選択した場合に領域を表示してくれるもので、実際は枠はありません。)
top
|
1 2 3 |
ZStack(alignment: .top){ … } |

topTrailing
|
1 2 3 |
ZStack(alignment: .topTrailing){ … } |

leading
|
1 2 3 |
ZStack(alignment: .leading){ … } |

center
|
1 2 3 |
ZStack(alignment: .center){ … } |

trailing
|
1 2 3 |
ZStack(alignment: .trailing){ … } |

bottomLeading
|
1 2 3 |
ZStack(alignment: .bottomLeading){ … } |

bottom
|
1 2 3 |
ZStack(alignment: .bottom){ … } |

bottomTrailing
|
1 2 3 |
ZStack(alignment: .bottomTrailing){ … } |

background
ZStack内のView領域を背景色で色付けしてみましょう。
|
1 2 3 4 5 6 7 8 9 10 |
// background ZStack{ Circle() .frame(width: 200, height: 200, alignment: .center) .foregroundColor(.orange) Text("ZStack") } .background(Color.blue) |

Color.blue で青色を指定しましたが、他の固定色は以下です。
- Color.black
- Color.blue
- Color.gray
- Color.green
- Color.orange
- Color.pink
- Color.red
- Color.white
- Color.yellow
frame
ZStackの領域をframeを使って限定してみます。
|
1 2 |
// frame の 横幅、縦長、フレーム内での位置 frame(width: CGFloat, height: CGFloat, alignment = .center) |
これを使ってZStackを使うとこうなります。
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// frame ZStack{ Circle() .frame(width: 200, height: 200, alignment: .center) .foregroundColor(.orange) Text("ZStack") } .frame(width:300, height:300, alignment: .center) |

またframeをSafe Areaまで広げることもできます。
|
1 2 3 4 5 6 7 8 9 10 11 |
ZStack{ Circle() .frame(width: 200, height: 200, alignment: .center) .foregroundColor(.orange) Text("ZStack") } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.green) |

References:
init(alignment:content:)
ZStack | Apple Developer Documentation
Alignment | Apple Developer Documentation
Color | Apple Developer Documentation
frame(width:height:alignment:) | Apple Developer