コード上で作成したビューを貼り付ける時、AutoLayoutをコードで書く必要があります。
しかし普通に書くと下のように長くなって可読性が低くなります。
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) self.view.addSubview(view) view.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addConstraints([ NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 100), NSLayoutConstraint(item: view, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 100), NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 0.0, constant: 100), NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.0, constant: 100), ] )
そこで今回はAutoLayout
をすっきりと設定できるSnapKit
を試してみます。
インストール
例のごとくPodfile
に下のように書いてpod install
するだけです。
use_frameworks! pod 'SnapKit'
使い方
使い方はしたの通りです。
かなりすっきり書けました。
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) self.view.addSubview(view) view.snp_makeConstraints(closure: { (make) -> Void in make.left.equalTo(100) make.top.equalTo(100) make.width.equalTo(100) make.height.equalTo(100) })
メソッドチェーンも使えるので下のようにwidthとheightを同時に設定する事もできます。
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) self.view.addSubview(view) view.snp_makeConstraints(closure: { (make) -> Void in make.left.top.equalTo(100) make.width.height.equalTo(100) })
下のようにwidthとheightを合わせたsizeというものや真ん中からのずれを表現するceterもあります。
view.snp_makeConstraints(closure: { (make) -> Void in make.size.equalTo(CGSize(width: 140, height: 150)) make.center.equalTo(CGPoint(x: 0, y: 0)) })