Subclassing UIView with NIB file

Here's how UIView subclassing is done (with NIB files). I felt the need of doing so for two reasons: reusability and maintainability.

Header class:
#import <UIKit/UIKit.h>

@interface MyCustomView: UIView

+ (MyCustomView *)createWithOwner:(id)owner;

@end

Implementation class:
#import "MyCustomView.h"

@implementation MyCustomView

+ (MyCustomView *)createWithOwner:(id)owner {
  NSString *nibName = NSStringFromClass([self class]);
  NSArray *nib = [[NSBundle mainBundle] loadNibNamed:nibName owner:owner options:nil];
  MyCustomView *view = [nib objectAtIndex:0];
  return view;
}

@end

Using the the new class is as simple as this:
#import "MyCustomView.h"

...

MyCustomView * customView = [MyCustomView createWithOwner:self];
[self.view addSubView: customView];
[customView release];  

...

Related posts:

Bookmark and Share

0 comments :

Post a Comment

Hi there! Please leave your message here. Also, I may not be able to respond to your query right away. So please bear with me. Thanks. :)