[SwiftUI] ZStackの配置、余白、背景色等の設定

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
 

alignment

 
ZStackはViewを重ねますが子Viewに対して alignment ができます。デフォルトはcenterですがその他八方向に配置が可能です。

 

topLeading

Circle図形と文字列のStackです。


(青い矩形枠はStackを選択した場合に領域を表示してくれるもので、実際は枠はありません。)

 

top


 

topTrailing


 

leading


 

center


 

trailing


 

bottomLeading


 

bottom


 

bottomTrailing


 

background

 
ZStack内のView領域を背景色で色付けしてみましょう。



 
Color.blue で青色を指定しましたが、他の固定色は以下です。

  • Color.black
  • Color.blue
  • Color.gray
  • Color.green
  • Color.orange
  • Color.pink
  • Color.red
  • Color.white
  • Color.yellow
 

frame

 
ZStackの領域をframeを使って限定してみます。


これを使ってZStackを使うとこうなります。


 
またframeをSafe Areaまで広げることもできます。


 
 

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


誤字脱字、意味不明などのご意見は 謙: e-mail まで
ブックマークしておくと便利です このエントリーをはてなブックマークに追加
Twitter:


シェアする

  • このエントリーをはてなブックマークに追加

フォローする