iOS_用Masonry实现 UIView Animation 简单动画

2022-07-20 14:52:24 浏览数 (1)

用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),在此记录一下~

0 人点赞