天天看點

[IOS]通過限制來改變控件位置

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.建立兩條限制,指向不同控件:

[IOS]通過限制來改變控件位置

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前的勾取消

[IOS]通過限制來改變控件位置
[IOS]通過限制來改變控件位置

把限制連結到代碼中,然後可以通過代碼來控制不同情況的展示了:

if (!_timeRadioGroup.hidden) {        NSLog(@"radio group:%i",_timeRadioGroup.hidden);
        [_align2ShowBtnConstraint setActive:YES];
        [_datePickerCenterConstraint setActive:NO];
    }