Skip to content

Instantly share code, notes, and snippets.

@hiragram
Last active April 6, 2016 01:54
Show Gist options
  • Select an option

  • Save hiragram/4a7d2e24272a1cde15160eed70588a4a to your computer and use it in GitHub Desktop.

Select an option

Save hiragram/4a7d2e24272a1cde15160eed70588a4a to your computer and use it in GitHub Desktop.
import Foundation
protocol NibInstantiatable {
static var nibName: String { get }
static func instantiateFromNibWithOwner(ownerOrNil: AnyObject?, options: [NSObject: AnyObject]?) -> Self
}
extension NibInstantiatable where Self: UIView {
static var nibName: String {
get {
return String(Self.self)
}
}
static func instantiateFromNibWithOwner(ownerOrNil: AnyObject?, options: [NSObject: AnyObject]?) -> Self {
return UINib(nibName: nibName, bundle: nil).instantiateWithOwner(ownerOrNil, options: options).first as! Self
}
}
@hiragram
Copy link
Author

hiragram commented Apr 6, 2016

Then you can instantiate any custom view like:

let awesome = AwesomeView.instantiateFromNibWithOwner(nil, options: nil)

And you only have to modify your custom view like:

- class AwesomeView: UIView {
+ final class AwesomeView: UIView, NibInstantiatable {

}

Bye-bye

let awesome = UINib(nibName: "AwesomeView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! AwesomeView

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment