Xcode7でInterface Builderを使わずに開発する
概要
- ViewはSwift(or Objective-C)のコードで組み立てる
- 生のAutoLayoutのコードは辛いからSnapKitを使う
まずやること
下記をやればInterface Builderから開放される。
- Main.storyboardを消す
- プロジェクト設定の Main Interface を空欄にする
- Launch Screen File は残しておく (これが設定されていないと画面引き伸ばしの設定になっちゃう)
- AppDelegateのエントリポイントを手動で設定する
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = ViewController() self.window?.makeKeyAndVisible() return true }
適当にViewを組み立ててみる
HogeViewクラスを適当に追加する。
import UIKit import SnapKit class HogeView: UIView { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(frame: CGRectZero) // must call designated initializer self.backgroundColor = UIColor.whiteColor() let wrapper = UIView() let element1 = UIView() let element2 = UIView() let label = UILabel() self.addSubview(wrapper) wrapper.addSubview(element1) wrapper.addSubview(element2) element2.addSubview(label) wrapper.backgroundColor = UIColor.cyanColor() element1.backgroundColor = UIColor.redColor() element2.backgroundColor = UIColor.greenColor() label.backgroundColor = UIColor.lightGrayColor() label.text = "hoge" wrapper.snp_makeConstraints { (make) -> Void in make.left.equalTo(self).inset(8) make.right.equalTo(self).inset(8) make.centerY.equalTo(self) make.height.equalTo(self).dividedBy(2) } element1.snp_makeConstraints { (make) -> Void in make.right.equalTo(wrapper).inset(8) make.bottom.equalTo(wrapper) make.width.equalTo(50) make.height.equalTo(wrapper).dividedBy(2) } element2.snp_makeConstraints { (make) -> Void in make.left.equalTo(wrapper).inset(8) make.right.equalTo(element1.snp_left) make.top.equalTo(wrapper).inset(8) make.bottom.equalTo(element1.snp_top) } label.snp_makeConstraints { (make) -> Void in make.center.equalTo(element2) } } }
ViewControllerの方ではこんなで。
import UIKit import SnapKit class ViewController: UIViewController { override func loadView() { self.view = HogeView() } }
こんな感じになる。
万歳!!!
AutoLayoutを脳内でプレビューできる場合はかなりやりやすいし、再利用もしやすいし、マージンとかを変数で管理することも簡単。最高!!
またコードでレイアウトを実装する時代に戻ろうではないか!!!!