Skip to content
Rex St. John

Get in touch

Custom UIView Subclasses With XIBs

Here is an easy way to make custom view subclasses out of Xib files: Header file: Implementation file: When you subclass this file, make sure to override...

Originally published on the rexstjohn.com blog

Originally published at rexstjohn.com on January 7, 2014. Recovered from the Internet Archive.

Here is an easy way to make custom view subclasses out of Xib files:

Header file:

#import 

@interface UXRSmartView : UIView

+ (NSString *)nibName;
+ (NSString *)viewIdentifier;
+ (id) viewSizedForDevice;

@end

Implementation file:

#import "UXRSmartView.h"

@implementation UXRSmartView

- (id)initWithFrame:(CGRect)frame
{
    id rootView = [[self class] viewSizedForDevice];
    [rootView setFrame:frame];
    self = rootView;
     
    if(self){
        // 
    }
    
    return self;
}

+ (id) viewSizedForDevice; {
    UINib* nib = [self nib];
    NSArray * nibObjects = [nib instantiateWithOwner:self options:nil];
    NSAssert2(([nibObjects count] > 0) &&
              [[nibObjects objectAtIndex:0] isKindOfClass:[self class]],
              @"Nib '%@' does not appear to contain a value %@",
              [self nibName], NSStringFromClass([self class]));
    id rootView = nibObjects[0];
    return rootView;
}

#pragma  mark - Smart Nib View

+(UINib*)nib; {
    NSBundle * classBundle = [NSBundle bundleForClass:[self class]];
    UINib * nib = [UINib nibWithNibName:[self nibName] bundle:classBundle];
    return nib;
}

+ (NSString *)nibName {
    return [self viewIdentifier];
}

+ (NSString *)viewIdentifier {
    [NSException raise:NSInternalInconsistencyException format:@"WARNING: YOU MUST OVERRIDE THIS GETTER IN YOUR CUSTOM VIEW .M FILE"];
    static NSString* _viewIdentifier = nil;
    _viewIdentifier = NSStringFromClass([self class]);
    return _viewIdentifier;
}
@end

When you subclass this file, make sure to override the identifier like this:

// MUST PROVIDE IDENTIFIER
+ (NSString *)viewIdentifier {
    static NSString* _viewIdentifier = @"UXRUserInfoHeaderView";
    _viewIdentifier = NSStringFromClass([self class]);
    return _viewIdentifier;
}

You will now be able to create a .Xib file for this custom view…make sure to set the class of the view in your Xib to match your parent class as well as the identifier.

When you use [[YourSubClass alloc] initWithFrame:], your view will now use your Xib file automatically.