AutoLayout之通过代码添加约束

//1.子控件禁用autorezing

view.translatesAutoresizingMaskIntoConstraints==NO;

//2.添加约束
/**
* Item : first item
* attribute : 约束
* relatedBy : =
* toItem : second item
* attribute : 约束
* multiplier : 乘以
* constant : 加上
*/

NSLayoutConstraint *constraint=[NSLayoutConstraint constraintWithItem:<#(id)#> attribute:<#(NSLayoutAttribute)#> relatedBy:<#(NSLayoutRelation)#> toItem:<#(id)#> attribute:<#(NSLayoutAttribute)#> multiplier:<#(CGFloat)#> constant:<#(CGFloat)#>]

/**
* VisualFormat : VFL语句
* options : 对齐方式
* metrics : 语句中的变量值
* views : 语句中用到的控件
*/

NSArray *constraint=[NSLayoutConstraint constraintsWithVisualFormat:<#(NSString *)#> options:<#(NSLayoutFormatOptions)#> metrics:<#(NSDictionary *)#> views:<#(NSDictionary *)#>]

//3.父子关系->添加到父控件上,兄弟关系->添加到父控件(self.view)上,

[self.view addConstraint:constraint];

//4.动画
如果控件有默认的内容(宽高), 我们只需设置autoalyout的X/Y, autolayout会自动计算出宽高
//约束连线

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftCos;

//修改约束的值

self.leftCos.constant += 100;

//执行动画

[UIView animateWithDuration:3 animations:^{
    // 让view上的约束执行动画
    [self.view layoutIfNeeded];
}];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章