iOS开发之使用UIView-Positioning简化页面布局

  使用过代码布局的人可能会有这样的感觉,给控件设置frame的时候比较繁琐。最 近在Github上看到有一个UIView的一个分类UIView-Positioning,这个分类提供了一些属性,比如left、right、 top、bottom、centerX、centerY等,在布局的时候使用这些属性,会更简单和方便,下面介绍下具体使用。

  UIView-Positioning的Github的地 址:https://github.com/freak4pc/UIView-Positioning,将UIView+Positioning.h和 UIView+Positioning.m文件拷贝到工程里面。

  在使用代码布局的时候,我一般习惯按照下面三个步骤去做:

1、声明控件变量。

@implementation LoginView
{
    UILabel *_userNameLabel;
    UITextField *_userNameField;
}
 2、在initWithFrame方法中,创建控件并设置它的一些基本属性,然后添加到View的子视图中。
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _userNameLabel = [UILabel new];
        _userNameLabel.font = [UIFont systemFontOfSize:14.0];
        _userNameLabel.textColor = [UIColor blackColor];
        _userNameLabel.backgroundColor = [UIColor clearColor];
        _userNameLabel.text = @"用户名:";
        [self addSubview:_userNameLabel];
        
        _userNameField = [UITextField new];
        _userNameField.font = [UIFont systemFontOfSize:14.0];
        _userNameField.textColor = [UIColor blackColor];
        _userNameField.borderStyle = UITextBorderStyleRoundedRect;
        [self addSubview:_userNameField];
    }
    return self;
}

3、在layoutSubViews方法里面对控件进行布局,下面使用 UIView-Positioning分类的size、left、top、bottom、centerY等属性,通过使用right属性,可以取到左边 Label控件的origin.x+size.width,然后加上一个padding值,就可以得到右边TextField控件的origin.x。平 时我们可能经常会碰到,要将两个不同高度的控件,设置为垂直方向对齐,我这里特意将这两个控件的高度设置得不一样,通过将它们的centerY属性设置为 相等,就可以保持这两个控件在垂直方向对齐了。

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat margin = 50, padding = 5;
    
    _userNameLabel.size = CGSizeMake(60, 15);
    _userNameLabel.left = margin;
    _userNameLabel.top = margin;
    
    _userNameField.size = CGSizeMake(200, 30);
    _userNameField.left = _userNameLabel.right + padding;
    _userNameField.centerY = _userNameLabel.centerY;
}
UIView-Positioning通过扩展了UIView的一些属性,为代码布局还是带来了挺大的方便,推荐大家可以使用一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值