1.创建一个CustomerView的文件,commend+n,如图:
2.用xib创建一个view,命名为CustomerView,commend+n,如图:
3.修改xib中如下数据,
3.1 首先修改Custom Class中的Class为:CustomerView,即建立与CustomerView的关联关系,如图:
3.2 在修改xib 的 Simulated Metrics 的参数值,即使view的大小可自动变化,如图:
4.使用xib代码:
#import <UIKit/UIKit.h>
@interface CustomerView : UIView
+(instancetype)customerView;
@end
#import "CustomerView.h"
@implementation CustomerView
+(instancetype)customerView
{
return [[[NSBundle mainBundle] loadNibNamed:@"CustomerView" owner:self options:nil] firstObject];
}
@end
//添加customerView
CustomerView *customerView = [CustomerView customerView];
customerView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
customerView.backgroundColor = [UIColor purpleColor];
[self.view addSubview:customerView];
注意:iOS用xib自定义view,修改不了frame的问题,主要是xib使用了autolayout布局页面,造成设置frame无效,所以去掉xib的autolayout布局(xib中把Use Auto layout的勾去掉,找到Simulated Metrics , 把Size 设置成None, 没有None就是Freeform)或者在drawRect中设置frame来解决(推荐后者),(例如:在UITableViewCell不能改变frame)
方法1:在“-(void)drawRect:(CGRect)rect”中设置:
frame明显设置不对cell的高度为100,xib的view中width=100,height=80,明显不对:
下边的frame才是正确的:
-(void)drawRect:(CGRect)rect
{
_customerView.frame = CGRectMake(50, 30, 100, 50);
}
方法2:stackoverflow上网友答案: