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.建立兩條限制,指向不同控件:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5CMyQzM5MWOyIGOzEDMyEWZyYzXzIzMxUTMzAzLchDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
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];
}