[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.创建两条约束,指向不同控件:

 

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可以决定哪个约束活动。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值