自定义视图步骤

自定义视图步骤

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.测试一下

自定义视图的好处: 提高工作效率 大大提高代码的复用性
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值