LoginSignup
9
10

More than 5 years have passed since last update.

Protocol Extension で ViewController のインスタンス化を簡単にする

Last updated at Posted at 2016-01-31

This Week in Swift で紹介されていた NibLoadableViewReusableView が便利です。

iOS Cell Registration & Reusing with Swift Protocol Extensions and Generics
https://gist.github.com/gonzalezreal/92507b53d2b1e267d49a

この protocol を使うと nibNamereuseIdentifier をハードコーディングせずに済みます:

    @IBOutlet weak var collectionView: UICollectionView! {
        didSet {
        //..
        collectionView.registerNib(
            UINib(nibName: MyCell.nibName, bundle: nil),
            forCellWithReuseIdentifier: MyCell.reuseIdentifier )
        }
    }

NibLoadableView にインパイアされて ViewController をインスタンス化するのに使うStoryboardInstantiatableViewController を作ってみました。

使いかた

Storyboard からインスタンスをつくる ViewController を StoryboardInstantiatableViewController のプロトコルに適合させるだけです:

extension SignupViewController: StoryboardInstantiatableViewController {}

ViewController のインスタンス化はこんな感じです:

        let viewController = UIStoryboard(name: SignupViewController.defaultStoryboardName, bundle: nil)
            .instantiateViewControllerWithIdentifier(SignupViewController.defaultStoryboardIdentifier)
        presentViewController(viewController, animated: true, completion: nil)

ソースコード

//StoryboardInstantiatableViewController.swift

import UIKit

public protocol StoryboardInstantiatableViewController: class {
    static var defaultStoryboardName: String { get }
    static var defaultStoryboardIdentifier: String { get }

}

public extension StoryboardInstantiatableViewController where Self: UIViewController {
    static var defaultStoryboardName: String {
        return NSStringFromClass(self).componentsSeparatedByString(".").last!
            .componentsSeparatedByString("ViewController").first!
    }
    static var defaultStoryboardIdentifier: String {
        return NSStringFromClass(self).componentsSeparatedByString(".").last!
    }
}
9
10
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
9
10