LoginSignup
2
1

More than 5 years have passed since last update.

[Swift4] NSNib.Nameの便利なExtensionとProtocol

Last updated at Posted at 2017-09-22

Swift4からNSNibを生成するためにXib(.nib)の名前をNSNib.Nameという特別なtypeにする必要が出来ました。

面倒くさいのでExtensionを作りました。

extension NSNib.Name {
    static func nibName<Subject>(_ type: Subject) -> NSNib.Name {
        return NSNib.Name(rawValue: String(describing: type))
    }
}

例えばCellItemクラスが使うクラスと同名のCellItem.xib(nib)をロードするときは、

let nib = NSNib(nibNamed: .nibName(CellItem.self), bundle: nil)

これでOKです。


追加
protocolも作りました。

protocol NibLoadable {

    static var nibName: NSNib.Name { get }
}

extension NibLoadable {

    static var nibName: NSNib.Name {

        return .nibName(for: self)
    }
}

これで、

extension CellItem: NibLoadable {}

とするだけで

let nib = NSNib(nibNamed: CellItem.nibName, bundle: nil)

とできるようになります。

2
1
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
2
1