iOS

masonry 使用优先级

iOS技术成长之路

Posted by DM on October 18, 2020

``` @interface ViewController ()

//设置三个View /*<#XXX#>/ @property (nonatomic , strong) UIView * orangeView;

/*<#XXX#>/ @property (nonatomic , strong) UIView * yellowView;

/*<#XXX#>/ @property (nonatomic , strong) UIView * greenView;

@end

@implementation ViewController

  • (void)viewDidLoad { [super viewDidLoad]; // NSLog(@”测试工程”); // self.view.backgroundColor = UIColor.redColor; self.orangeView = [[UIView alloc]init]; self.orangeView.backgroundColor = [UIColor orangeColor]; [self.view addSubview:self.orangeView];

    UIView *yellowView = [[UIView alloc]init]; yellowView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:yellowView]; self.yellowView = yellowView;

    UIView *greenView = [[UIView alloc]init]; greenView.backgroundColor = [UIColor greenColor]; [self.view addSubview:greenView]; self.greenView = greenView;

//配置约束 [self setUpRestrain]; [self.orangeView removeFromSuperview]; // [self.yellowView removeFromSuperview]; [self.view setNeedsLayout]; }

//配置约束 -(void)setUpRestrain { __weak typeof( self) weakSelf = self;

//对于橙色View只需正常设置约束就好 [self.orangeView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.height.mas_equalTo(100); make.left.equalTo(weakSelf.view).offset(20); make.top.offset(50); }]; // 黄色View只会发生一次变化,就多设一个优先级较低的约束就好 [self.yellowView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.height.mas_equalTo(100); make.left.offset(20); make.top.equalTo(weakSelf.orangeView.mas_bottom).offset(20); //当橙色View消失后,黄色View缺少左边约束,所以给其加一个优先级更低的左边约束。当第一个左边约束失效后,这个约束就起作用了 make.top.equalTo(weakSelf.view).offset(50).priority(300);

  }];   //同理绿色View的低级约束就得设置两个    [self.greenView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.width.height.mas_equalTo(100);
      make.left.offset(20);
   make.top.equalTo(weakSelf.yellowView.mas_bottom).offset(20).priority(379);

     make.top.equalTo(weakSelf.orangeView.mas_bottom).offset(20).priority(300);

      make.top.equalTo(weakSelf.view).offset(50).priority(200);
  }];

}

```