自定义视图步骤
1.创建一个继承自UIView类
@interface LTView : UIView
2.重写新类的初始化方法
3.把想添加的视图封装到新类里(初始化到新类)
-- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
获取动态宽度
CGFloat width = frame.size.width;
获取动态高度
CGFloat height = frame.size.height;
根据上面的宽度 来添加label
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,(width / 3), height)];
self.label.backgroundColor = [UIColor yellowColor];
添加到自己身上
[self addSubview:self.label];
[_label release];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(width / 3 + 20, 0, (width - width / 3 - 20), height)];
self.textField.backgroundColor = [UIColor greenColor];
[self addSubview:self.textField];
[_textField release];
}
return self;
}
4.为了方便外部进行赋值或者取值 把添加的视图写成属性(别忘了释放)
@property (nonatomic,retain)UILabel *label;
@property (nonatomic,retain)UITextField *textField;
有属性就要释放
- (void)dealloc
{
[_label release];
[_textField release];
[super dealloc];
}
5.测试一下