実行結果の画面。
Xcode で新規に Single View Application のプロジェクトを作成して、以下のサンプルコードを ViewController.swift に貼り付ければ完成。
//
// ViewController.swift
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .green
// ラベルを生成
let myLabel = UILabel()
myLabel.text = "center"
myLabel.textAlignment = .center
myLabel.textColor = .red
myLabel.backgroundColor = .blue
// Autosizing を constraints に適用しない
myLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(myLabel);
// constraints を設定
self.view.addConstraints([
// init(item:attribute:relatedBy:toItem:attribute:multiplier:constant:) - NSLayoutConstraint | Apple Developer Documentation
// https://developer.apple.com/reference/uikit/nslayoutconstraint/1526954-init
// x座標: self.viewの中心と同じ中心位置を設定
NSLayoutConstraint(
item: myLabel, // 対象となる要素
attribute: .centerX, // 対象となる要素の constraint の位置
relatedBy: .equal, // 2つの要素の関係性
toItem: self.view, // 基準となる要素
attribute: .centerX, // 基準となる要素 constraint の位置
multiplier: 1.0, // constraint の割合
constant: 0), // multiplier の後の追加分
// y座標: self.viewの中心と同じ中心位置を設定
NSLayoutConstraint(
item: myLabel,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view,
attribute: .centerY,
multiplier: 1.0,
constant: 0),
// 横幅: self.viewの50%の大きさ
NSLayoutConstraint(
item: myLabel,
attribute: .width,
relatedBy: .equal,
toItem: self.view,
attribute: .width,
multiplier: 0.5,
constant: 0),
// 縦高: 固定44ピクセル
NSLayoutConstraint(
item: myLabel,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1.0,
constant: 44),
])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
今回の環境は Xcode Version 8.1 + Apple Swift version 3.0.1
- ref.
- [ヅ] Swift コードだけで実現する Auto Layout constraint 制約サンプル (複数の項目を配置) (2016-11-17)
- Auto Layoutをコードから使おう
- init(item:attribute:relatedBy:toItem:attribute:multiplier:constant:) - NSLayoutConstraint | Apple Developer Documentation
- Auto Layout (AutoLayout - MemoWiki)
tags: swift iphone ios
Posted by NI-Lab. (@nilab)