LoginSignup
29
30

More than 5 years have passed since last update.

構造体でStoryboardとNibを管理する

Last updated at Posted at 2015-09-28

追記
rizumita/ResourceInstantiatableとしてGitHubに上げました。StoryboardとNibだけでなく、NSBundleで取得できるFileにも対応しました。


iOS - Protocolを利用してStoryboardやXibファイルからインスタンスを生成する - Qiitaという記事を書いたが、今度は構造体でStoryboardとNibを管理してみる。

protocol ResourceInstantiatable {
    typealias InstanceType
    func instantiate() -> InstanceType
    func instantiate(configure: (InstanceType -> Void)?) -> InstanceType
}
extension ResourceInstantiatable {
    func instantiate(configure: (InstanceType -> Void)?) -> InstanceType {
        let instance = instantiate()
        configure?(instance)
        return instance
    }
}

struct ResourceManager {

    static var viewController = Storyboard<ViewController>(name: "Other")
    static var secondViewController = Storyboard<SecondViewController>(name: "Other", identifier: "SecondViewController")
    static var sampleView = Nib<SampleView>(name: "SampleView")

}

struct Storyboard<T: UIViewController>: ResourceInstantiatable {
    typealias InstanceType = T

    let name: String
    let identifier: String?

    func instantiate() -> InstanceType {
        let storyboard = UIStoryboard(name: name, bundle: nil)
        if let identifier = identifier {
            return storyboard.instantiateViewControllerWithIdentifier(identifier) as! InstanceType
        } else {
            return storyboard.instantiateInitialViewController() as! InstanceType
        }
    }

    init(name: String, identifier: String? = nil) {
        self.name = name
        self.identifier = identifier
    }
}

struct Nib<T: UIView>: ResourceInstantiatable {
    typealias InstanceType = T

    let name: String

    func instantiate() -> InstanceType {
        let nib = UINib(nibName: name, bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).first as! InstanceType
    }

    init(name: String) {
        self.name = name
    }
}

使い方は以下のようになる。

let controller = StoryboardManager.secondViewController.instantiate()

iOS - Protocolを利用してStoryboardやXibファイルからインスタンスを生成する - Qiitaに比べてリソースを一元管理できて分かりやすいかもしれない。

29
30
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
29
30