Last active
April 8, 2018 01:53
-
-
Save tcirwin/b7d990f927123c9f2403 to your computer and use it in GitHub Desktop.
Load view from xib using class name
This file contains 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
+ (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; | |
} |
This file contains 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
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