zoukankan      html  css  js  c++  java
  • iOS动态管理AutoLayout的约束NSLayoutConstraint

    除了使用Storyboard之外,也可以使用使用代码的方式,动态的向指定的UIView,添加约束。

    例如有两个UILabel:someLabel,otherLabel

    首先用代码实例化,两个控件

    self.someLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    self.someLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.inputContainerView];
    
    self.otherLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    self.otherLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.inputContainerView];

    两点很重要:

    1. translatesAutoresizingMaskIntoConstraints = NO  否则布局就会混乱
    2. someLabel和otherLabel必须有superView,否则就会出现出现警告

    The view hierarchy is not prepared for the constraint

    When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.

    运行时候Crash

    Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal

    例如新建了一个UIView的Category

    其中一个方法

    -(NSLayoutConstraint*)verticalDistanceTop:(UIView*)topView constant:(CGFloat)constant
    {
        NSLayoutConstraint*topConstrant = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:topView     attribute:NSLayoutAttributeBottom multiplier:1 constant:constant];
        return topConstrant;
    }

    返回一个约束,保证self具体topView的底部距离为contant

    约束的构造函数 :constraintWithItem,注意计算公式:

    view1.attr1 = view2.attr2 * multiplier + constant

    /* Create constraints explicitly.  Constraints are of the form "view1.attr1 = view2.attr2 * multiplier + constant" 
     If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute.
     */
    +(instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(nullable id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;

    生成约束后,使其生效的方法

     NSLayoutConstraint*topConstraint = [self.someLabel verticalDistanceTop:self.otherLabel constant:22];
        topConstraint.active = YES;
  • 相关阅读:
    shell 指定范围产生随机数
    shell脚本比较两个数大小
    Shell 脚本实现随机抽取班级学生
    linux通过挂载系统光盘搭建本地yum仓库的方法
    kuberenetes 上使用helm部署rancher如何卸载干净
    Windows 下 左Ctrl和Caps交换
    C#笔记 -- 协变、逆变
    Python 读取window下UTF-8-BOM 文件
    生成命令行程序使用脚本
    ffmpeg 命令小记
  • 原文地址:https://www.cnblogs.com/taojigu/p/4905114.html
Copyright © 2011-2022 走看看