This Week in Swift で紹介されていた NibLoadableView
と ReusableView
が便利です。
iOS Cell Registration & Reusing with Swift Protocol Extensions and Generics
https://gist.github.com/gonzalezreal/92507b53d2b1e267d49a
この protocol を使うと nibName
や reuseIdentifier
をハードコーディングせずに済みます:
@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!
}
}