一、如何從xib自定義一個CustomView
1)首先創建繼承自UIView的子類CustomView
2)創建名字為CustomView的View的Interface文件
3)在xib的資源文件中修改class為CustomView
4)編輯xib,拖拽控件
代碼如下:
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activity;
xib 如下

注意class類型

5)使用這個自定義的view
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self test2];
}
- (void)test1
{
CustomView *v = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];
[self.view addSubview:v];
v.center = self.view.center;
v.activity.backgroundColor = [UIColor redColor];
}
6)結果

二、如何繼承一個從xib初始化的view
目前還沒有這樣的方法,蘋果已經不推薦使用xib初始化view這樣的方式了。
放棄繼承,使用組合的方式來實現
頭文件
@interface MyView : UIView
{
UIView *view;
UILabel *l;
}
@property (nonatomic, retain) IBOutlet UIView *view;
@property (nonatomic, retain) IBOutlet UILabel *l;
實現
#import "MyView.h"
@implementation MyView
@synthesize l, view;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// Initialization code.
//
[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
[self addSubview:self.view];
}
return self;
}
- (void) awakeFromNib
{
[super awakeFromNib];
// commenters report the next line causes infinite recursion, so removing it
// [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
[self addSubview:self.view];
}
- (void) dealloc
{
[l release];
[view release];
[super dealloc];
}
