LoginSignup
5
5

More than 5 years have passed since last update.

プログラムで親ビューの上下左右マージンゼロで制約をつける(Swift)

Last updated at Posted at 2016-05-20

WKWebView など Interface builder 上で追加できないビューを self.view に上下左右マージンゼロで貼り付けたい時にプログラムから指定する際のコード。

どこでも使えるように UIView の Extension として作成した。

UIView+AutoLayout.swift

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)
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5