代码手动修改约束(AutoLayout)

当使用xib或storyBoard构建项目,并使用了AutoLayout之后,当需要为视图添加动画,或者手动更改视图的frame的时候,就需要修改约束啦.别以为代码中修改约束很麻烦,其实还蛮简单的啦.

例如: 跟随键盘弹出的ToolBar,原来在视图底部,当键盘弹出时,ToolBar跟随键盘弹出

  • 首先将ToolBar到底部的约束添加一个IBOutlet
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolViewBottomConstraint;
  • 键盘弹出修改约束
//键盘的通知(显示)
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSValue* aValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSNumber *durationValue = [notification userInfo][UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration = durationValue.doubleValue;

    [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        _toolViewBottomConstraint.constant = keyboardRect.size.height;//修改距离底部的约束
    } completion:^(BOOL finished) {
    }];    
    [self.view setNeedsLayout]; //更新视图
    [self.view layoutIfNeeded];
}

下面来看下,如何删除和增加约束 最后,附个addConstraint 函数的意义: view1.attr1 = view2.attr2 * multiplier + constant

 [self.view removeConstraint:_sinaLeftDistance];//在父试图上将iSinaButton距离屏幕左边的约束删除

  NSLayoutConstraint *myConstraint =[NSLayoutConstraint
                        constraintWithItem:iSinaButton //子试图
                        attribute:NSLayoutAttributeCenterX //子试图的约束属性
                        relatedBy:NSLayoutRelationEqual //属性间的关系
                        toItem:self.view//相对于父试图
                         attribute:NSLayoutAttributeCenterX//父试图的约束属性
                         multiplier:1.0 
                         constant:0.0];// 固定距离

[self.view addConstraint: myConstraint];//为iSinaButton重新添加一个约束



文/好好姐(简书作者)
原文链接:http://www.jianshu.com/p/5ae4d59abc4a
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文地址:https://www.cnblogs.com/gaohe/p/5799605.html