·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS开发之使用UIView-Positioning简化页面布局

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

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

  使用过代码布局的人可能会有这样的感觉,给控件设置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的一些属性,为代码布局还是带来了挺大的方便,推荐大家可以使用一下。