縦向きスタックビューを1つだけ使って、ラベル、画像ビュー、ボタンをレイアウト
事前準備
サンプルコードをダウンロードして解凍
Single View Applicationでプロジェクトを作成
Project Nameは適当に
必要なファイルのインポート
- プロジェクト名の書かれたフォルダアイコンを右クリックして、『Add Files to "プロジェクト名"』を選択
- ダウンロードして解凍しておいたフォルダから、Auto Layout Cookbook->Assets.xcassets->flowers.imagesetの中にあるflowers.pngとflowers@2x.pngを選択(適当なGroupを作ってまとめておくと良い)
View Controller内のViewにVertical Stack Viewを配置
普通に画面にドラッグ&ドロップでViewに配置される
Stack ViewにFlowers Labelを配置
- Stack ViewにLabelを配置
- LabelのAttribute InspectorからLabel Text(初期値はLabel)をFlowersにする
Stack ViewにImage Viewを配置
Flowers Labelの下に来るように
Stack ViewにButtonを配置
Image Viewの下に来るように
Stack Viewに制約(Constraints)を設定
Stack Viewを選択して、Pinから
- Top(上)はTop Layout GuideとUse Standard Valueを選択(Stack View.Top = Top Layout Guide.Bottom + Standard)
- Leading(左)はViewを選択して、Constrain to Marginsにチェックを入れ値を0に(Stack View.Leading = Superview.LeadingMargin)
- Trailing(右)はViewを選択して、Constrain to Marginsにチェックを入れ値を0に(Stack View.Trailing = Superview.TrailingMargin)
- Bottom(下)はBottom Layout GuideとUse Standard Valueを選択(Bottom Layout Guide.Top = Stack View.Bottom + Standard)
Constraintsは4つ同時でも、1つずつでも設定できるが、Add Constraintsを押さないと設定されない
Constraintsが正しく設定されているかどうかは、View Controller Sceneのツリーを展開したり、Stack ViewのSize Inspectorを開いたりして確認できる
Stack Viewの属性を設定
Stack ViewのAttributes Inspectorで
- Axis(軸)をVertical
- Alignment(整列)をFill
- Distribution(配分)をFill
- Spacing(間隔)を8
に設定
Image Viewの属性を設定
Image ViewのAttributes Inspectorで
- Imageをflowers.png
- ModeをAspect Fill
に設定
Image ViewのSize Inspectorで
- Content Hugging Priority(収縮性の優先度)
- Horizontalを250
- Verticalを249
- Content Compression Resistence Priority(膨張性の優先度)
- Horizontalを750
- Verticalを749
に設定