LoginSignup
6

More than 5 years have passed since last update.

swiftgenを使ってsegueIdentierとか管理する

Last updated at Posted at 2015-11-26

iosアプリ開発時の問題点としてsegue Idntiferとか文字列なのでtypoをコンパイル時検出できなかったりします。
androidだとR.javaというのがあるらしいですね。
http://qiita.com/ksoichiro/items/4befb2695b1efdff72dd

手動でenumを作ってもいいんですが
swiftgenを使うとstoryboardからidentiferを取り出してenumで管理してくれるようになるようです。

インストール

homebrewを使っている前提です。

brew install swiftgen

xcodeでbuild時に自動生成させる

swiftgen.png

プロジェクトトップ > Targets(main) > Build Phases
+ボタンを選んでnew runs script phase

以下のコードを追加

swiftgen storyboards ${SRCROOT}/${PRODUCT_NAME}/Base.lproj/Main.storyboard > ${SRCROOT}/${PRODUCT_NAME}/storyboardAutoGen.swift

storyboardの置き場所が
<<プロジェクト名>>/Base.lproj/Main.storyboardであることが前提です。

以降ビルド時にコード生成が進みます。
生成されるコードはこんな感じ

// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen

import Foundation
import UIKit

protocol StoryboardScene {
  static var storyboardName : String { get }
}

extension StoryboardScene {
  static func storyboard() -> UIStoryboard {
    return UIStoryboard(name: self.storyboardName, bundle: nil)
  }

  static func initialViewController() -> UIViewController {
    return storyboard().instantiateInitialViewController()!
  }
}

extension StoryboardScene where Self: RawRepresentable, Self.RawValue == String {
  func viewController() -> UIViewController {
    return Self.storyboard().instantiateViewControllerWithIdentifier(self.rawValue)
  }
  static func viewController(identifier: Self) -> UIViewController {
    return identifier.viewController()
  }
}

protocol StoryboardSegue : RawRepresentable { }

extension UIViewController {
  func performSegue<S : StoryboardSegue where S.RawValue == String>(segue: S, sender: AnyObject? = nil) {
    performSegueWithIdentifier(segue.rawValue, sender: sender)
  }
}

extension UIStoryboard {
  struct Scene {
    enum Main : StoryboardScene {
      static let storyboardName = "Main"
    }
  }

  struct Segue {
    enum Main : String, StoryboardSegue {
      case ToCameraViewController = "toCameraViewController"
      case ToPhotoConfirmViewController = "toPhotoConfirmViewController"
    }
  }
}


使い方

befoe:

performSegueWithIdentifier("toCameraViewController", sender: nil)

after:

performSegue(UIStoryboard.Segue.Main.ToCameraViewController , sender: nil)

参考:

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
6