Skip to content

Instantly share code, notes, and snippets.

@ndfred
Created June 14, 2012 10:49
Show Gist options
  • Save ndfred/2929581 to your computer and use it in GitHub Desktop.
Save ndfred/2929581 to your computer and use it in GitHub Desktop.
Load a view from a nib file
+ (id)nibLoadedView {
BOOL isTableViewCell = [self isSubclassOfClass:[UITableViewCell class]];
UIView *view = isTableViewCell ? [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(self)] : [[self alloc] initWithFrame:CGRectZero];
UINib *nib = [UINib nibWithNibName:[self nibName] bundle:nil];
UIView *rootView = [[nib instantiateWithOwner:view options:nil] lastObject];
if (![rootView isKindOfClass:self]) {
view.frame = rootView.frame;
view.backgroundColor = rootView.backgroundColor;
if (isTableViewCell) {
UIView *rootContentView = [(UITableViewCell *)rootView contentView];
UIView *contentView = [(UITableViewCell *)view contentView];
for (UIView *subview in rootContentView.subviews.copy) {
[contentView addSubview:subview];
}
} else {
for (UIView *subview in rootView.subviews.copy) {
[view addSubview:subview];
}
}
rootView = view;
}
[rootView viewDidLoad];
return rootView;
}
+ (id)nibLoadedView {
BOOL isTableViewCell = [self isSubclassOfClass:[UITableViewCell class]];
UIView *view = isTableViewCell ? [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(self)] : [[self alloc] initWithFrame:CGRectZero];
UINib *nib = [UINib nibWithNibName:[self nibName] bundle:nil];
UIView *rootView = [[nib instantiateWithOwner:view options:nil] lastObject];
if (![rootView isKindOfClass:self]) {
view.frame = rootView.frame;
view.backgroundColor = rootView.backgroundColor;
if (isTableViewCell) {
UIView *rootContentView = [(UITableViewCell *)rootView contentView];
UIView *contentView = [(UITableViewCell *)view contentView];
for (UIView *subview in rootContentView.subviews.copy) {
[contentView addSubview:subview];
}
} else {
for (UIView *subview in rootView.subviews.copy) {
[view addSubview:subview];
}
}
rootView = view;
}
[rootView viewDidLoad];
return rootView;
}
+ (NSString *)nibName {
return NSStringFromClass(self);
}
- (void)viewDidLoad {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment