视图布局

UIViewController生命周期:
  • -(void)viewDidLoad ;
  • -(void)viewWillAppear:(BOOL)animated;
  • -(void)viewWillLayoutSubviews;
  • -(void)viewDidLayoutSubviews;
  • -(void)viewDidAppear:(BOOL)animated;
  • -(void)viewDidDisappear:(BOOL)animated;
  • -(void)viewWillDisappear:(BOOL)animated;

其中will/DidLayoutSubviews方法有是可以多次被调用执行的

  1. 改变view的frame, 或改变subView的frame,
    如横竖屏变换或设置/更新subview的frame或 mas_updateConstraints:(更新约束)
  2. 添加子视图 addSubviews
  3. 直接视图直接调用 [self.view setNeedsLayout];

PS: 线束即时生效:

[UIView animateWithDuration:0.3
                 animations:^{
                              [self.view layoutIfNeeded];
                     }];
LayoutSubViews相关
  1. -(void)layoutSubviews默认不做任何事情,需要子类重写
  2. -(void)setNeedsLayout 调用layoutSubviews,但并不立即刷新。
    仅做需要刷新的标记
  3. -(void)layoutIfNeeded并不必然调用layoutSubviews,除非标记需要刷新。
自定义View updateConstraints相关
// 重写+requiresConstraintBasedLayout
// 返回YES就是明确告诉系统:保证系统初始化视图一定会调用 -updateConstraints 方法
// 如果不写则初始时不会调用
+ (BOOL)requiresConstraintBasedLayout{
    return YES;
}
- (void)updateConstraints {
    
    [self.growingButton updateConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.equalTo(@(self.buttonSize.width));
        make.height.equalTo(@(self.buttonSize.height));
        make.width.lessThanOrEqualTo(self);
        make.height.lessThanOrEqualTo(self);
    }];
//
    //一定要调用父视图方法
    [super updateConstraints];
}

回调方法

- (void)didTapButton:(UIButton *)button {
    self.buttonSize = CGSizeMake(self.buttonSize.width * 1.3, self.buttonSize.height * 1.3);

    // 告诉self.view约束需要更新
    [self setNeedsUpdateConstraints];

    //self.view检测是否需要更新约束,若需要则更新,下面添加动画效果才起作用
    [self updateConstraintsIfNeeded];
   
    //添加动画
    [UIView animateWithDuration:0.4 animations:^{
        [self layoutIfNeeded];
    }];

  
}

你可能感兴趣的:(视图布局)