一、如何從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];
}
參考,https://stackoverflow.com/questions/5056219/uiview-and-initwithframe-and-a-nib-file-how-can-i-get-the-nib-file-loaded?noredirect=1&lq=1
轉載于:https://www.cnblogs.com/doudouyoutang/p/10731782.html