代码手动修改约束(AutoLayout)

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

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolViewBottomConstraint;


_toolViewBottomConstraint.constant = keyboardRect.size.height;//修改距离底部的约束
//键盘的通知(显示)
- (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];
}

 [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重新添加一个约束

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

你可能感兴趣的:(iOS,iOS移动开发)