iOSアプリ開発で、多様な画面サイズに対してViewのレイアウトを設定するにはAutoLayoutを使用します。
今回ライブラリーを使わずに、AutoLayoutをコードで実装する方法をまとめました。
AutoLayoutとは
AutoLayoutとは、多様な画面サイズに対してViewのレイアウトを適用させる仕組みになります。
各Viewに制約(Constraint)を設定してレイアウトを決めていきます。
基本的な制約は以下になります。
制約 | |
---|---|
leading | 左側 |
trailing | 右側 |
top | 上方 |
bottom | 下方 |
width | 幅 |
height | 高さ |
centerX | 水平方向の中央 |
centerY | 垂直方向の中央 |
コードでAutoLayoutを設定する方法を紹介します。
AutoLayoutの方法
- NSLayoutConstraint
- NSLayoutAnchor
- Visual Format Language (VFL)
AutoLayoutをコードで実装
赤い四角形(100x100)のviewを、画面中央に配置するサンプルを記載します。

環境
- Xcode 11
- Swift 5
NSLayoutConstraint
let view1 = UIView()
view1.backgroundColor = .red
view.addSubview(view1)
view1.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints([
NSLayoutConstraint( // 幅100
item: view1,
attribute: .width,
relatedBy: .equal,
toItem: view,
attribute: .width,
multiplier: 0.0,
constant: 100
),
NSLayoutConstraint( // 高さ100
item: view1,
attribute: .height,
relatedBy: .equal,
toItem: view,
attribute: .height,
multiplier: 0.0,
constant: 100
),
NSLayoutConstraint( // 水平方向中央
item: view1,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0
),
NSLayoutConstraint( // 垂直方向中央
item: view1,
attribute: .centerY,
relatedBy: .equal,
toItem: view,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0
)
])
NSLayoutAnchor
NSLayoutAnchorは、iOS9で追加されました。
こちらの方が簡潔に書くことができるので、ライブラリーを使用しない場合はこれが一番おすすめです。
let view1 = UIView()
view1.backgroundColor = .red
view.addSubview(view1)
view1.translatesAutoresizingMaskIntoConstraints = false
view1.widthAnchor.constraint(equalToConstant: 100).isActive = true // 幅100
view1.heightAnchor.constraint(equalToConstant: 100).isActive = true // 高さ100
view1.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true // 水平方向中央
view1.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true // 垂直方向中央
Visual Format Language (VFL)
レイアウトをコードから把握しやすいメリットがあります。
しかし文字列で制約を設定するため、タイプミスしても実行されるまで分からないデメリットがあります。
let view1 = UIView()
view1.backgroundColor = .red
view.addSubview(view1)
let views: [String: UIView] = ["view1": view1, "view": view]
view1.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-(<=1)-[view1(width)]", options: .alignAllCenterX, metrics: ["width" : 100], views: views) + // 幅100の水平方向中央
NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-(<=1)-[view1(height)]", options: .alignAllCenterY, metrics: ["height" : 100], views: views) // 高さ100の垂直方向中央
)