注意:这个View是父视图 view1 和 view2 是互相约束的
注意:尽量view2 为同一个层级 这样循环加view1的时候容易计算
view1.translatesAutoresizingMaskIntoConstraints = false
View.addSubview(view1)
View.addConstraint(NSLayoutConstraint(
item: <#AnyObject#>, 指定约束左边的视图view1
attribute: <#NSLayoutAttribute#>, 指定view1的属性attr1
relatedBy: <#NSLayoutRelation#>, 指定左右两边的视图的关系relation
toItem: <#AnyObject?#>, 指定约束右边的视图view2
attribute: <#NSLayoutAttribute#>, 指定view2的属性attr2
multiplier: <#CGFloat#>, 指定一个与view2属性相乘的乘数multiplier
constant: <#CGFloat#>)) 指定一个与view2属性相加的浮点数constant
公式:view1.attr1 <relation> view2.attr2 * multiplier + constant
eg:
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:view2
attribute:NSLayoutAttributeRight
multiplier:1
constant:10]
代码意思是: view1的左侧,在,view2的右侧,再多10个点,的地方。
NSLayoutRelation:
typedef NS_ENUM(NSInteger, NSLayoutRelation) {
NSLayoutRelationLessThanOrEqual = -1, //小于等于
NSLayoutRelationEqual = 0, //等于
NSLayoutRelationGreaterThanOrEqual = 1, //大于等于
};
NSLayoutAttribute:
typedef NS_ENUM(NSInteger, NSLayoutAttribute) {
NSLayoutAttributeLeft = 1, //左侧
NSLayoutAttributeRight, //右侧
NSLayoutAttributeTop, //上方
NSLayoutAttributeBottom, //下方
NSLayoutAttributeLeading, //首部
NSLayoutAttributeTrailing, //尾部
NSLayoutAttributeWidth, //宽度
NSLayoutAttributeHeight, //高度
NSLayoutAttributeCenterX, //X轴中心
NSLayoutAttributeCenterY, //Y轴中心
NSLayoutAttributeBaseline, //文本底标线
NSLayoutAttributeNotAnAttribute = 0 //没有属性
};
//水平约束NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[greenView]-20-[yellowView(==greenView)]-20-|", options: 0, metrics: nil, views: [view1 : view2])
//垂直约束 NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[greenView]-20-[yellowView(==greenView)]-20-|", options: 0, metrics: nil, views: [view1 : view2])
//修改约束
UIView.animateWithDuration(0.3, animations: { () -> Void in
//有时需要
superview.layoutIfNeeded()
self.layoutIfNeeded()
self.deleteLabel.layoutIfNeeded()
})
网友评论