31
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AutoLayoutをDSL風に記述できるSnapKit

Last updated at Posted at 2015-11-21

レイアウトをInterfaceBuilderを使わずにコードで生成する場合に何とも可読性の低いコードになってしまいます。
そこでAutoLayoutをDSL風に記述できてしまうSnapKitを使ってみたよ、という記録。

##SnapKitインストール
まず適当にプロジェクトを作ってCocoaPodからSnapkitをインストールします。
以下のようなPodfileを用意します。

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'SnapKit', '~> 0.15.0'

そしてpod installします。

##使ってみよう

まず先頭で「import SnapKit」しておきます。
あとはこんな感じ。

let label1 = UILabel()
label1.font = UIFont.systemFontOfSize(32)
label1.numberOfLines = 4
label1.text = "古池や"
label1.textColor = UIColor.blackColor()
label1.sizeToFit()

self.view.addSubview(label1)
label1.snp_makeConstraints { (make) -> Void in
    make.leading.equalTo(view).offset(240)
    make.top.equalTo(view).offset(8)
    make.width.equalTo(45)
    make.height.equalTo(200)
}

let label2 = UILabel()
label2.font = UIFont.systemFontOfSize(32)
label2.numberOfLines = 4
label2.text = "蛙飛込む"
label2.textColor = UIColor.blackColor()

view.addSubview(label2)
label2.snp_makeConstraints { (make) -> Void in
    make.leading.equalTo(view).offset(180)
    make.top.equalTo(view).offset(48)
    make.width.equalTo(45)
    make.height.equalTo(200)
}

let label3 = UILabel()
label3.font = UIFont.systemFontOfSize(32)
label3.numberOfLines = 4
label3.text = "池の音"
label3.textColor = UIColor.blackColor()

view.addSubview(label3)
label3.snp_makeConstraints { (make) -> Void in
    make.leading.equalTo(view).offset(120)
    make.top.equalTo(view).offset(88)
    make.width.equalTo(45)
    make.height.equalTo(200)
}

これを動かすとこうなります。
screen1.png

NSLayoutConstraintを直接使う場合に比べるとかなり見やすいんじゃないでしょうか。

31
35
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
31
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?