• 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的一些属性,为代码布局还是带来了挺大的方便,推荐大家可以使用一下。

     
  • 相关阅读:
    PPT中的图像失真
    Delphi GDI对象之绘制文本
    iOS App的加固保护原理
    PHP网站渗透中的奇技淫巧:检查相等时的漏洞
    企业安全建设之浅谈数据防泄露
    常见分布式全局唯一ID生成策略及算法的对比
    写时模式”与“读时模式”之间的对比
    工业互联网环境下IT/OT融合的安全防御技术研究
    一文梳理工业控制系统信息安全软件与监控
    威努特iSoc培训
  • 原文地址:https://www.cnblogs.com/hnsdwhl/p/4604063.html
Copyright © 2020-2023  润新知