您的位置:首页 > 其它

用Xib自定义一个View

2016-07-20 14:23 357 查看
1. 新建一个继承于View的类,再建一个有view的xib文件,选中这个xib的file’s Owner,修改Custom Class .







2. 把size选成FreeForm,这样你就可以随意的调整View的大小了



3.在Xib上布局好



4. 下面就是如何使用这个Xib。有两种方法。

使用代码方法初始化。

*先把xib的view设置成一个属性。



*然后在自定义的view中,写入代码

- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self awakeFromNib];
}
return self;
}
- (void)awakeFromNib{
self.contentView = [[[NSBundle mainBundle]loadNibNamed:@"WeiShopHeaderView" owner:self options:nil]lastObject];
self.contentView.frame = self.bounds;
[self addSubview:self.contentView];
}


使用方法:

//需要设置frame。
WeiShopHeaderView *head = [[WeiShopHeaderView alloc]initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 290)];
head.frame = CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 290);
[self.view addSubview:head];


2.直接Xib初始化。

WeiShopHeaderView *head = [[[NSBundle mainBundle]loadNibNamed:@"WeiShopHeaderView" owner:self options:nil]lastObject];

[self.view addSubview:head];

//vfl 自动布局
head.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *viewsDict = NSDictionaryOfVariableBindings(head);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[head]|"
options:0
metrics:nil
views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[head(290)]" options:0 metrics:nil views:viewsDict]];

head.backgroundColor = [UIColor redColor];






这样就可以正常的使用Xib自定义的View了,(配色真难看。)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Xib 自定义 View