Skip to content

Instantly share code, notes, and snippets.

@chakrit
Created February 13, 2012 05:57
Show Gist options
  • Save chakrit/1814072 to your computer and use it in GitHub Desktop.
Save chakrit/1814072 to your computer and use it in GitHub Desktop.
Objective-C custom XIB-based UIView stub
#import <UIKit/UIKit.h>
@interface CWView : UIView
// for child class to override and change the behavior (if needed)
@property (nonatomic, readonly) BOOL useNib;
@end
#import "CWView.h"
#import <objc/runtime.h>
@implementation CWView
- (id)initWithFrame:(CGRect)frame { // designated
if (!(self = [super initWithFrame:frame]))
return self; // init error
if (!self.useNib)
return self; // doesn't use nib, so we're done.
// load the nib and return the object inside instead
const char *className = class_getName([self class]);
NSString *nibName = [NSString stringWithCString:className encoding:NSASCIIStringEncoding];
NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil];
if (!objects)
return self = nil;
id realSelf = [objects objectAtIndex:0];
if (!realSelf)
return realSelf;
[self release];
self = realSelf;
[self setFrame:frame];
return [self retain];
}
- (BOOL)useNib {
// default to having a nib
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment