天天看点

107 代码约束 VFL语言

1.在xib上添加的每个约束都是一个约束对象,可以通过代码的方式添加约束

1>首先需要将添加约束的view的translatesAutoresizingMaskIntoConstraints属性为NO(禁用autoresizng)

2>只是约束自己的添加在自己的身上(例如宽高)

3>约束相对于父控件要添加在父控件身上(例如距离左边间隔)

4>两个同级之间的view的约束添加到父控件身上(例如两个同级view之间的间隔)

/*
     Item == first item 需要设置约束的控件
     attribute == 需要设置的约束
     relatedBy == relation   等于
     toItem == second item    被参照的控件
     attribute == 需要设置的约束
     multiplier == multiplier  乘以
     constant = constant   加上
     */
   //添加约束使自己的左边距离父控件的左边的距离为20
    NSLayoutConstraint *leftCos = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier: constant:];
    [self.view addConstraint:leftCos];
           

2.VFL语言

1>为了简化代码添加约束的复杂的,apple推出AFL语言用于约束

2>在VFL语句中, 是不支持乘除法

//使用VFL语言添加约束,blueView在水平方向想距离左边20,右边20
    int margin = ;
    NSArray *blueViewH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-margin-[blueView]-margin-|" options: metrics:@{@"margin": @(margin)} views:@{@"blueView" : blueView}];
    [self.view addConstraints:blueViewH];