1.創(chuàng)建UIView 的SubClass 命名為MainHeaderView
2.創(chuàng)建一個(gè)名為MainHeaderView的xib
3.配置xib的屬性
4.設(shè)置xib中的File’s owner = MainHeaderView, 拖拽view 到關(guān)聯(lián)的代碼中命名為contentView
5.對(duì)ViewController 初始化MainHeaderView
-
MainHeaderView.m中添加代碼
- (void)awakeFromNib
{
[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
[self addSubview:self.contentView];
}
7.這樣執(zhí)行后就可以看到該View了炒瘟,但是會(huì)有一個(gè)嚴(yán)重的問(wèn)題州刽,那就是MainHeaderView 在顯示時(shí)沒(méi)有做到AutoLayout行贪。僅僅是按照xib中的尺寸來(lái)顯示爽雄,而在實(shí)際應(yīng)用中可能我們會(huì)期待在ViewController中使用的自定義View內(nèi)部亦可以自動(dòng)匹配大小粥帚。
對(duì)于上面的問(wèn)題靡馁,我的解決方法是重寫(xiě)setFrame方法虾宇,如下:
8暴凑、MainHeaderView.m中添加代碼
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
CGRect rect = frame;
rect.origin.x = 0;
rect.origin.y = 0;
self.contentView.frame = rect;
}
MainHeaderView中代碼如下:
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
CGRect rect = frame;
rect.origin.x = 0;
rect.origin.y = 0;
self.m_ContentView.frame = rect;
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self initial];
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.frame = frame;
[self initial];
}
return self;
}
- (void)initial
{
[[NSBundle mainBundle] loadNibNamed:@"MainHeaderView" owner:self options:nil];
[self addSubview:self.m_ContentView];
}
9.viewcontroller中實(shí)現(xiàn)
self.s_HeadView = [[MainHeaderView alloc] init];
[self.s_HeadView setFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 160)];
以上即可