iOS 通过constraint 进行autolayout的动画

来源:互联网 发布:大数据电信应用教程 编辑:程序博客网 时间:2024/04/29 09:06

现在知道了如果我们使用了xib 或者是SB 进行布局 关联的子view是无法进行view修改frame,就算你修改了 也没有用,这不是意味着就能去改变这个view的布局了 ,首先我们必须要改变他的 约束,通过改变约束从而实现改变。好了 废话不多说 来实践一下

就以输入框的  输入的时候 界面向上抬起 为例子,当然 一般的做法是 点击 textfield  触发textfield代理 方法

textFieldDidBeginEditing  当结束 输入的时候执行  textFieldDidEndEditing 方法。好了 这是准备工作 ,原来常用的方法是点击输入框判断高度

self.view 抬起,这样可以不用去care frame的不改变的问题了,但是如果加一个子view 里面加入textfield的话 你想实现让子view向上抬起就不行,

加了约束 是为了做适配,如果不加,适配 就会非常的麻烦,好了 废话不多说。



关联属性 通过改变constraint的里面constant来实现布局的改变





接下来就是在上面说的函数里面添加方法了

constraint是 iOS 6.0 以后引入的

#pragma mark -adjustViewWithkeyboard;

-(void)textFieldDidBeginEditing:(UITextField *)textField{


    if(NSFoundationVersionNumber >NSFoundationVersionNumber_iOS_7_1){

        

        self.downConstraint.active =YES;

        self.downConstraint.constant =0;

        [UIViewanimateWithDuration:0.5animations:^{

            [self.viewlayoutIfNeeded];

        }];

        

    }else{

        [changeAcountView.superviewremoveConstraint:self.upConstraint];

        [changeAcountView.superviewremoveConstraint:self.downConstraint];

        [changeAcountView.superviewaddConstraint:self.upConstraint];

        [UIViewanimateWithDuration:0.5animations:^{

            [self.viewlayoutIfNeeded];

        }];

    } 

}


-(void)textFieldDidEndEditing:(UITextField *)textField{


   //ios 7引入的

    if(NSFoundationVersionNumber >NSFoundationVersionNumber_iOS_7_1){

        self.downConstraint.active =YES;

        self.downConstraint.constant =60;

        [UIViewanimateWithDuration:0.5animations:^{

            [self.viewlayoutIfNeeded];

        }];

        

    }else{

  self.downConstraint.constant = 60;

        [changeAcountView.superviewremoveConstraint:self.downConstraint];   //移除原来的 添加新的 当然你也可以不这样做

        [changeAcountView.superviewaddConstraint:self.downConstraint];

        [UIViewanimateWithDuration:0.5animations:^{

         [self.viewlayoutIfNeeded];

        }];

    }

}

contraint 特别说明一下

遍历其superview上的constraints

数组通过constraint属性的判断来找到这个约束(和父view之间的约束都只放在父view

的constraints属性里而不是自己的constraints属性中)


0 0
原创粉丝点击