1.约束构造器:
NSLayoutConstraint(item: ViewObject1, attribute: NSLayoutAttribute1, relatedBy: NSLayoutRelation, toItem: ViewObject2, attribute: NSLayoutAttribute2, multiplier: CGFloatMultiplier, constant: CGFloatConstant ) ViewObject1 - the view from which we are constraining NSLayoutAttribute1 - An NSLayoutAttribute, ex. Left, Right, Leading, Trailing, see full list here NSLayoutRelation - An NSLaoyoutRelation, determines the relation between 2 attributes. Example Leading Edge of View Equals Leading Edge of SuperView. The possible values are LessThanOrEqual, Equal, GreaterThanOrEqual. see full details here ViewObject2 - is the second vew to which we are constraining NSLayoutAttribute2 - The constraint addribute for the second view, ex Leading, Trailing, Width, etc CGFloatMultiplier - The multiplier applied to the second attribute participating in the constraint. CGFloatConstant - The value of the constraint. Ex. 20 points from the superview
例子:
NSLayoutConstraint *center = [NSLayoutConstraint constraintWithItem:_datePicker attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_networkEnabled attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
2.查看第二个依赖控件:
[_setTimeTvTopConstraint secondItem]
3.创建两条约束,指向不同控件:
4.在代码中建立约束的链接:
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *setTimeTvTopConstraint; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *setTimeTvTopPwdConstraint;
5.只需要在Remain Time 控件隐藏时,调整
_setTimeTvTopPwdConstraint.constant = 22;
即可自动上移。
注意:在storyboard中定义的约束,relation firstItem secondItem都是只读属性,修改不了,固定了。如果不想重新控件画图,暂时发现只能通过这种约束方式来移动。
6.通过不同情况来添加或删除约束:
例如某些情况下靠边,某些情况下居中:
先设置靠边约束,然后设置居中约束,但是把installed前的勾取消
把约束链接到代码中,然后可以通过代码来控制不同情况的展示了:
if (!_timeRadioGroup.hidden) { NSLog(@"radio group:%i",_timeRadioGroup.hidden); [_align2ShowBtnConstraint setActive:YES]; [_datePickerCenterConstraint setActive:NO]; }
setActive可以决定哪个约束活动。