LoginSignup
3
3

More than 5 years have passed since last update.

StoryboardやXib読み込み用ヘルパー関数

Last updated at Posted at 2015-05-26

使い方

  • Storyboard

class MyViewController: UIViewController {
    var myProp: Int = 0
}

extension MyViewController: Storyboardable {

    class var storyboardIdentifier: String { return "MyViewController" }
    class var storyboardName: String { return "MyStoryboard" }

}


let vc = from_storyboard(MyViewController.self)
vc.myProp = 1

  • Xib

class MyView: UIView {
    var myProp: Int = 0
}

extension MyView: Xibable {
    class var xibName: String { return "MyView" }
}


let view = from_xib(MyView.self)
view.myProp = 1

実装

protocol Storyboardable {

    static var storyboardIdentifier: String { get }
    static var storyboardName: String { get }
}

func from_storyboard<T: AnyObject where T: Storyboardable>(clazz: T.Type) -> T! {

    let identifier = T.storyboardIdentifier
    let name = T.storyboardName

    let storyboard = UIStoryboard(name: name, bundle: nil)
    return storyboard.instantiateViewControllerWithIdentifier(identifier) as? T
}

protocol Xibable {

    static var xibName: String { get }
}

func from_xib<T: AnyObject where T: Xibable>(clazz: T.Type, owner: AnyObject? = nil, options: [NSObject: AnyObject]? = nil, atIndex index: Int = 0) -> T! {

    let name = T.xibName

    let xib = UINib(nibName: name, bundle: nil)
    return xib.instantiateWithOwner(owner, options: options)[index] as? T
}

3
3
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
3
3