Skip to content

Instantly share code, notes, and snippets.

@tcirwin
Last active April 8, 2018 01:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tcirwin/b7d990f927123c9f2403 to your computer and use it in GitHub Desktop.
Save tcirwin/b7d990f927123c9f2403 to your computer and use it in GitHub Desktop.
Load view from xib using class name
+ (id)loadViewForClass:(Class)klass {
NSString *klassName = NSStringFromClass(klass);
NSArray *views = [[NSBundle mainBundle] loadNibNamed:klassName
owner:nil
options:nil];
for (id view in views) {
if ([view isKindOfClass:klass]) {
return view;
}
}
NSAssert(NO, @"No view with class %@ found in %@.xib", klassName, klassName);
return nil;
}
class func loadView<Cell: UIView>() -> Cell {
let className = String(describing: Cell.self)
let nib = Bundle.main.loadNibNamed(className, owner: nil, options: nil)
for item in (nib ?? []) {
if let item = item as? Cell {
return item
}
}
assertionFailure(String(format: "[Utils] Failed to find class of type %@ in nib named %@", String(describing: Cell.self), className))
return UIView() as! Cell
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment