Created
May 20, 2018 04:17
-
-
Save sahara-ooga/3e2cf888ed73bd6801dac1d4fd8a69d9 to your computer and use it in GitHub Desktop.
「モバイルアプリ開発エキスパート養成読本」より「タイプセーフでモダンなiOSアプリの設計」
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
任意のUIViewControllerのサブクラスに対して、Storyboardableを適応することによって、 | |
Storyboardから該当のUIViewControllerの型でインスタンスを取得できるようになります。 | |
*/ | |
extension NSObjectProtocol { | |
static var className: String { | |
return String(describing: self) | |
} | |
} | |
protocol Storyboardable: NSObjectProtocol { | |
static var storyboardName: String { get } | |
static func instantiate() -> Self | |
} | |
extension Storyboardable where Self: UIViewController { | |
static var storyboardName: String { | |
return className | |
} | |
static func instantiate() -> Self { | |
return UIStoryboard( | |
name: storyboardName, | |
bundle: Bundle(for: self) | |
).instantiateInitialViewController() as! Self | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
カスタムセルのTypeを渡すだけでUITableViewに登録でき、 | |
そのセルのインスタンスをUITableViewから取得できるようになります。 | |
*/ | |
protocol Nibable: NSObjectProtocol { | |
static var nibName: String { get } | |
static var nib: UINib { get } | |
} | |
extension Nibable { | |
static var nibName: String { | |
return className | |
} | |
static var nib: UINib { | |
return UINib(nibName: nibName, bundle: Bundle(for: self)) | |
} | |
} | |
extension UITableViewCell { | |
/// クラス名を返す | |
static var identifier: String { | |
return className | |
} | |
} | |
extension UITableView { | |
/// TableViewにセルのnibを登録する | |
/// | |
/// - Parameter cellType: UITableViewCellのクラス名 | |
/// - NOTE: セルに対してNibファイルは一つという前提 | |
func register<T: UITableViewCell>(_ cellType: T.Type) where T: Nibable { | |
register(T.nib, forCellReuseIdentifier: T.identifier) | |
} | |
/// コードでレイアウトが定義されているカスタムセルを登録する | |
/// | |
/// - Parameter cellType: UITableViewCellのクラス名 | |
func register<T: UITableViewCell>(_ cellType: T.Type) { | |
register(T.self, forCellReuseIdentifier: T.identifier) | |
} | |
/// UITableViewからカスタムセルを取得する | |
/// | |
/// - Parameters: | |
/// - cellType: 取得したいセルのクラス名 | |
/// - indexPath: 取得したいセルの位置 | |
/// - Returns: 指定したカスタムセルクラスのインスタンス | |
func dequeReusableCell<T:UITableViewCell>(with cellType: T.Type, | |
for indexPath: IndexPath) -> T { | |
return dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as! T | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment