Masonry简单动画效果的实现-新

iOS开发在frame定位的时代,如果要想实现简单的移动动画,只需在下面这个方法的block里重写frame就可以实现

[UIViewanimateWithDuration:0.5 animations:^{ 

      //在这重写frame 

}];

 

而在autolayout的时代,我们没法重写frame,要想实现动画,我们可以重写约束,直接上代码

 

   self.view5 = [[UIView alloc] init];

    self.view5.backgroundColor = [UIColor greenColor];

    [self.view addSubview:self.view5];

    

    Bself(bself);   //弱引用

    //添加约束

    [self.view5 mas_makeConstraints:^(MASConstraintMaker *make) {

        

        //距顶上300

        make.top.equalTo(bself.view).with.offset(300);

        //水平居中

        make.centerX.equalTo(bself.view);

        //固定宽

        make.width.mas_equalTo(@150);

        //固定高

        make.height.mas_equalTo(@60);

    }];

    

    

    //建个button

    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.backgroundColor = [UIColor blueColor];

    [button addTarget:self action:@selector(clickedButton) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

    

    [button mas_makeConstraints:^(MASConstraintMaker *make) {

        

        make.top.equalTo(bself.view).with.offset(100);

        make.centerX.equalTo(bself.view);

        make.width.mas_equalTo(@100);

        make.height.mas_equalTo(@50);

    }];

//button点击方法

- (void)clickedButton

{

    static BOOL isMove; //默认是NO

    Bself(bself);

    

    if (isMove) {

        

        isMove = NO;

        

        //添加动画

        [UIView animateWithDuration:0.5 animations:^{

            

            [bself.view5 mas_updateConstraints:^(MASConstraintMaker *make) {

                

                //更改距顶上的高度

                make.top.equalTo(bself.view).with.offset(300);

            }];

            //必须调用此方法,才能出动画效果(需要实现动画的view的父视图进行调用)

           [bself.view layoutIfNeeded];

        }];

    }

    else{

        

        isMove = YES;

        

        //开始动画

        [UIView beginAnimations:nil context:nil];

        //设定动画持续时间

        [UIView setAnimationDuration:1];

        

        [bself.view5 mas_updateConstraints:^(MASConstraintMaker *make) {

            

            //动画的内容,更改距顶上的高度

            make.top.equalTo(bself.view).with.offset(200);

        }];

        //必须调用此方法,才能出动画效果(需要实现动画的view的父视图进行调用)

        [bself.view layoutIfNeeded];

        //动画结束

        [UIView commitAnimations];

    }

}

这样就实现了每点击一次button,view5就上移100或下移100;就得一定要加上layoutIfNeeded方法刷新布局,不然无动画效果。还有bself是

 

#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;

 

这个其实没有必要,因为不会引起循环引用。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值