WKWebView など Interface builder 上で追加できないビューを self.view に上下左右マージンゼロで貼り付けたい時にプログラムから指定する際のコード。
どこでも使えるように UIView の Extension として作成した。
extension UIView {
// 親ビュー (parent) に対して上下左右マージンゼロの指定をする
func applyAutoLayoutMatchParent(parent: UIView, margin: CGFloat = 0) {
self.translatesAutoresizingMaskIntoConstraints = false
let attributes: [NSLayoutAttribute] = [.Top, .Left, .Right, .Bottom]
let constraints = attributes.map { (attribute) -> NSLayoutConstraint in
return NSLayoutConstraint(
item: self,
attribute: attribute,
relatedBy: .Equal,
toItem: parent,
attribute: attribute,
multiplier: 1.0,
constant: margin
)
}
parent.addConstraints(constraints)
}
}
使い方は以下のように呼び出す。
webView.applyAutoLayoutMatchParent(self.view)
8 px あけたいなどの場合は、以下のように margin 指定。
webView.applyAutoLayoutMatchParent(self.view, margin: 8)