[iOS]よく使うSwiftライブラリ SnapKit編

 #はじめに
ここまではRxSwift、Rx系のSwiftライブラリを見てきましたが、前回のRxKeyboardのプロジェクトで出てきた、SnapKitというのが、かなり有用だそうなので、こちらを取り上げていきたいと思います。

#作るもの
<img width="464" alt="スクリーンショット 2019-08-07 18.16.39.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/468725/c366031a-b6ce-d1bc-f7de-65b5580e8c94.png">


#環境
Xcode10.3
Swift5.0.1
RxSwift 5.0.0
RxCocoa 5.0.0
SnapKit 5.0.0


#準備

1.プロジェクト作成

-Xcodeを起動 
-Create a new Xcode project 
　＞Single View App
　＞Product Name:SnapKitSample
　＞完了。すぐにプロジェクトを閉じます。

2.ターミナルを起動して、ディレクトリに移動

```
$ cd SnapKitSample
```

3.Podfile作成/編集

```
$ pod init
$ vi Podfile
```

PodFileを以下に修正します。

```:Podfile
target 'SnapKitSample' do
  use_frameworks!

  pod 'RxSwift'
  pod 'RxCocoa'  
  pod 'SnapKit'

end
````


4.ライブラリのインストール

```
$ pod install
```

5.プロジェクトを開く
.xcworkspaceから起動する


#Storyboardを削除
今回は、Storyboardもxibも使わずに、プログラムに直書きでレイアウトを表示します。

1.Main.storyboardの削除
/Main.storyboardをDelete > Move to Trash

2.Info.plist
Info.plistを開く ＞ Main storyboard file base nameの項目を削除(マイナスボタン)

#実装

AppDelegateを以下のように修正します。

```AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    //こうすることでSwift4.1以下でもdidFinishLaunchingWithOptionsが呼ばれるようにできる
    #if swift(>=4.2)
        typealias ApplicationLaunchOptionsKey = UIApplication.LaunchOptionsKey
    #else
        typealias ApplicationLaunchOptionsKey = UIApplicationLaunchOptionsKey
    #endif
    
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [ApplicationLaunchOptionsKey: Any]?
        ) -> Bool {

        let window = UIWindow(frame: UIScreen.main.bounds)
        window.backgroundColor = .white
        window.makeKeyAndVisible()
        
        let viewController = ViewController()
        let navigationController = UINavigationController(rootViewController: viewController)
        window.rootViewController = navigationController
        
        self.window = window
        return true
    }
}
```

```ViewController.swift
import UIKit
import SnapKit

class ViewController: UIViewController {

    var didSetupConstraints: Bool = false
    let container: UIView = UIView()
    let labelFullWidth: UILabel = UILabel()
    let labelHalfWidth: UILabel = UILabel()
    let labelQuarter: UILabel = UILabel()
    let label80Percent: UILabel = UILabel()
    let label20Percent: UILabel = UILabel()
    let label40Percent: UILabel = UILabel()
    let label10Percent: UILabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupViews()
    }

    fileprivate func setupViews() {
        
        //エイリアス定義
        typealias Content = (title: String, label: UILabel, color: UIColor)
        
        let font: UIFont? = UIFont(name: "Menlo-Bold", size: 15)
        
        let green: UIColor = UIColor(hue: 0.40, saturation: 0.77, brightness: 0.80, alpha: 1.0)
        let yellow: UIColor = UIColor(hue: 0.13, saturation: 0.99, brightness: 0.80, alpha: 1.0)
        let blue: UIColor = UIColor(hue: 0.57, saturation: 0.76, brightness: 0.86, alpha: 1.0)
        let purple: UIColor = UIColor(hue: 0.70, saturation: 0.52, brightness: 0.77, alpha: 1.0)
        let red: UIColor = UIColor(hue: 0.02, saturation: 0.74, brightness: 0.91, alpha: 1.0)
        let pink: UIColor = UIColor(hue: 0.90, saturation: 0.49, brightness: 0.96, alpha: 1.0)
        let navy: UIColor = UIColor(hue: 0.12, saturation: 0.25, brightness: 0.94, alpha: 1.0)
        
        let contents: [Content] = [
            ("100%", labelFullWidth, green),
            ("50%", labelHalfWidth, yellow),
            ("1/4", labelQuarter, blue),
            ("80%", label80Percent, purple),
            ("20%", label20Percent, red),
            ("40%", label40Percent, pink),
            ("10%", label10Percent, navy),
        ]
        
        //すべてのラベルの共通設定
        for content in contents {
            let label = content.label
            label.font = font
            label.textAlignment = .center
            label.backgroundColor = content.color
            label.textColor = .black
            label.layer.opacity = 0.9
            label.text = content.title
            
            container.addSubview(label)
        }
        
        view.addSubview(container)
        view.backgroundColor = .white
        view.setNeedsUpdateConstraints()
    }
    
    override func updateViewConstraints() {
        
        if !didSetupConstraints {
            
            container.snp.makeConstraints{ make in
                
                //inset:内側余白 > padding
                make.edges.equalToSuperview().inset(
                    UIEdgeInsets(
                        top:view.safeAreaInsets.top,
                        left: 30,
                        bottom: view.safeAreaInsets.bottom,
                        right: 30)
                )

                //親ビューの中心と同じ位置に
                make.center.equalToSuperview()
            }
            
            labelFullWidth.snp.makeConstraints { make in
                make.width.equalToSuperview()
                make.height.equalTo(100)
                
                //オブジェクトの上辺をメインビューの中心Yに
                make.top.equalTo(view.snp.centerY)
                
                //widthが親ビューと一緒なので、左端から右端まで100%になる
                make.left.equalToSuperview()
            }
            
            labelHalfWidth.snp.makeConstraints { make in
                make.width.equalToSuperview().multipliedBy(0.5) //倍率表示
                make.height.equalTo(100)
                make.bottom.equalTo(view.snp.centerY)
                make.left.equalToSuperview()
            }
            
            labelQuarter.snp.makeConstraints { make in
                make.width.equalToSuperview().dividedBy(2)  //横2分割と
                make.height.equalToSuperview().dividedBy(2) //縦2分割の大きさで1/4の面積になる
                make.bottom.equalTo(view.snp.centerY)
                make.left.equalTo(view.snp.centerX)
            }
            
            label80Percent.snp.makeConstraints { make in
                make.width.equalToSuperview().multipliedBy(0.8)
                make.top.equalTo(labelFullWidth.snp.bottom)
                make.bottom.equalToSuperview()
                make.right.equalToSuperview()
            }
            
            label20Percent.snp.makeConstraints { make in
                make.width.equalToSuperview().multipliedBy(0.2)
                make.height.equalTo(label80Percent)
                make.top.equalTo(labelFullWidth.snp.bottom)
                make.left.equalToSuperview()
            }
            
            label40Percent.snp.makeConstraints { make in
                make.width.equalToSuperview().multipliedBy(0.4)
                make.top.equalToSuperview()
                make.left.equalToSuperview()
                make.bottom.equalTo(labelHalfWidth.snp.top)
            }
            
            label10Percent.snp.makeConstraints { make in
                make.width.equalToSuperview().multipliedBy(0.1)
                make.top.equalToSuperview()
                make.left.equalTo(label40Percent.snp.right)
                make.bottom.equalTo(labelHalfWidth.snp.top)
            }
            
            didSetupConstraints = true
        }
        
        super.updateViewConstraints()
    }
}

```


#参考
https://tech.ryukyu-i.co.jp/2016/12/02/easy-to-use-snapkit/
https://github.com/tdkn/EasyToUseSnapKit/blob/master/EasyToUseSnapKit/Sample02ViewController.swift