前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS_用Masonry实现 UIView Animation 简单动画

iOS_用Masonry实现 UIView Animation 简单动画

作者头像
mikimo
发布2022-07-20 14:52:24
1.1K0
发布2022-07-20 14:52:24
举报
文章被收录于专栏:iOS开发~iOS开发~

用Masonry实现 UIView Animation 简单动画

其实只需要在mas_updateConstraints:设置完需要更新的layout之后调用父视图的layoutIfNeeded方法就行。

代码语言:javascript
复制
@interface MOViewTestViewController ()
@property (nonatomic, strong) UIView *moView;
@end

@implementation MOViewTestViewController {
    BOOL _isOn;
}

- (void)viewDidLoad {
	[super viewDidLoad];    
    // 用masonry写动画
    [self createButton];
    [self createView];
}

/// 点击:触发动画
- (void)clickBtn:(UIButton *)sender {
    // 如果其约束还没有生成的时候需要动画的话,就需要先强制刷新后再写动画
    // 否则还没生成约束就会直接跑动画,得不到想要的动画效果
    // [self.moView.superview layoutIfNeeded];
    
    [UIView animateWithDuration:3 animations:^{
        [self.moView mas_updateConstraints:^(MASConstraintMaker *make) {
            if (self->_isOn) {
                make.width.mas_equalTo(@50);
                make.height.mas_equalTo(@50);
            } else {
                make.width.mas_equalTo(@100);
                make.height.mas_equalTo(@100);
            }
            self->_isOn = !self->_isOn;
        }];
        [self.moView.superview layoutIfNeeded]; // 强制绘制 (重点是这句)
    }];
}

- (void)createView {
    self.moView = [[UIView alloc] initWithFrame:CGRectZero];
    self.moView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.moView];
    
    [self.moView.superview layoutIfNeeded];
    [self.moView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.width.mas_equalTo(@50);
        make.height.mas_equalTo(@50);
    }];
}

- (void)createButton {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"animation" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor redColor];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(@100);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(@60);
        make.height.mas_equalTo(@44);
    }];
}

面试的时候被问到过(因为Resume里写了Masonry),在此记录一下~

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-07-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 用Masonry实现 UIView Animation 简单动画
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档