使用xib自定義一個簡單的控件 XMGShopView
xib效果圖:
運行時效果圖:
xib自定義控件的創(chuàng)建方法:
- 通過init方法創(chuàng)建
XMGShopView *shopView = [[XMGShopView alloc] init];
shopView.frame = CGRectMake(100, 100, 90, 110);
[self.view addSubview:shopView];
運行效果:- 通過initWithFrame:方法創(chuàng)建
XMGShopView *shopView = [[XMGShopView alloc] initWithFrame: CGRectMake(200, 200, 90, 110)];
[self.view addSubview:shopView];
運行效果:- 通過loadNibNamed: 方法創(chuàng)建
/*
xib總結(jié):
1.在Xcode中xib,被打包到應(yīng)用程序中是.nib文件
2.如果從xib加載的View沒有設(shè)置尺寸,則描述xib時的尺寸,就是View的尺寸
*/
XMGShopView *shopView = [[[NSBundle mainBundle] loadNibNamed:@"XMGShopView" owner:nil options:nil] firstObject];
shopView.frame = CGRectMake(100, 100, 90, 110);
[self.view addSubview:shopView];
運行效果:
- 通過nibWithNibName:方法創(chuàng)建
/*
// 注意:如果mainBundle作為參數(shù)時,傳入nil也可以
UINib *nib = [UINib nibWithNibName:@"XMGShopView" bundle:[NSBundle mainBundle]];
*/
UINib *nib = [UINib nibWithNibName:@"XMGShopView" bundle:nil];
XMGShopView *shopView = [[nib instantiateWithOwner:nil options:nil] firstObject];
shopView.frame = CGRectMake(200, 200, 90, 110);
[self.view addSubview:shopView];
運行效果:
xib創(chuàng)建注意點:
- 通過xib加載控件,不會執(zhí)行init方法和initWithFrame方法
- 會執(zhí)行initWithCoder方法和awakeFromNib方法
- 如果想通過xib加載控件時,一定不能通過[Class alloc] init]方法來創(chuàng)建控件
- 通常會讓類提供一個類方法,該類方法可以快速從xib中創(chuàng)建View
+ (instancetype)shopView{
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] firstObject];
}
通過xib自定義控件,基本控件中只能給UIview控件添加子控件,UIImageView、UILabe、UIButton等控件不能在xib中添加子空間只能通過代碼添加子控件
通過代碼給xib中iconView添加子控件
- 通過initWithCoder:方法給iconView添加子控件(實際并不會成功)
/**
* 如果View從xib中加載,就會調(diào)用initWithCoder:方法
* 創(chuàng)建子控件,...
注意: 如果子控件是從xib中創(chuàng)建,是處于未喚醒狀態(tài)
*/
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
label.backgroundColor = [UIColor grayColor];
label.text = @"給image控件添加子控件";
[self.iconView addSubview:label];
}
return self;
}
運行時效果圖:
- 在awakeFromNib給xib中iconView添加子控件
/**
* 從xib中喚醒
添加 xib中創(chuàng)建的子控件 的子控件
*/
- (void)awakeFromNib{
UILabel *label = [[UILabel alloc] initWithFrame:self.iconView.bounds];
label.backgroundColor = [UIColor grayColor];
label.numberOfLines = 0;
label.text = @"給image控件添加子控件";
[self.iconView addSubview:label];
}
運行效果:
這篇筆記參考小碼哥視頻整理的如有侵權(quán)敬請告知。