NSLayoutConstraint的使用

准备阶段:
  新建storyboard,加入viewController    记为:testViewController
  新建testViewController.h,testViewController.m文件

方法一:
1.于testViewController加入控件UIView view2
2.于testViewController.h对view2进行关联
3.添加约束:

  //该约束解释:view2的宽度为当前view宽度的2/3

  float wdith=self.view.frame.size.width/3;
  [self.view2 addConstraint:[NSLayoutConstraint constraintWithItem:
         self.view2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:wdith*2]];

注:

[NSLayoutConstraint constraintWithItem:(id)item
                             attribute:(NSLayoutAttribute)attribute
                             relatedBy:(NSLayoutRelation)relation
                                toItem:(id)otherItem
                             attribute:(NSLayoutAttribute)otherAttribute
                            multiplier:(CGFloat)multiplier
                              constant:(CGFloat)constant]

第一个参数:指定约束左边的视图view1

第二个参数:指定view1的属性attr1,具体属性见文末。

第三个参数:指定左右两边的视图的关系relation,具体关系见文末。

第四个参数:指定约束右边的视图view2

第五个参数:指定view2的属性attr2,具体属性见文末。

第六个参数:指定一个与view2属性相乘的乘数multiplier

第七个参数:指定一个与view2属性相加的浮点数constant

重点说明:如果你想设置的约束里不需要第二个view,要将第四个参数设为nil,第五个参数设为NSLayoutAttributeNotAnAttribute

实例:

[NSLayoutConstraint constraintWithItem:view1
                             attribute:NSLayoutAttributeLeft
                             relatedBy:NSLayoutRelationEqual
                                toItem:view2
                             attribute:NSLayoutAttributeRight
                            multiplier:1
                              constant:100]
解释:view1的左侧,在view2的右侧,再多10个点的地方。

附视图的属性和关系的值:
typedef NS_ENUM(NSInteger, NSLayoutRelation) {
    NSLayoutRelationLessThanOrEqual = -1,          //小于等于
    NSLayoutRelationEqual = 0,                     //等于
    NSLayoutRelationGreaterThanOrEqual = 1,        //大于等于
};
typedef NS_ENUM(NSInteger, NSLayoutAttribute) {
    NSLayoutAttributeLeft = 1,                     //左侧
    NSLayoutAttributeRight,                        //右侧
    NSLayoutAttributeTop,                          //上方
    NSLayoutAttributeBottom,                       //下方
    NSLayoutAttributeLeading,                      //首部
    NSLayoutAttributeTrailing,                     //尾部
    NSLayoutAttributeWidth,                        //宽度
    NSLayoutAttributeHeight,                       //高度
    NSLayoutAttributeCenterX,                      //X轴中心
    NSLayoutAttributeCenterY,                      //Y轴中心
    NSLayoutAttributeBaseline,                     //文本底标线
                                                                                                                                                    
    NSLayoutAttributeNotAnAttribute = 0            //没有属性
};


  

原文地址:https://www.cnblogs.com/shareze/p/4074214.html