Masonry设置约束优先级[转]

原文:http://www.jianshu.com/p/b0e1797036fe

 

#####前言:以前看到那种布局好的界面,当其中一个控件消失后,其余控件自动调整约束,还不知道怎么实现。 下去学习了一下,其实就是设置约束有先级的问题。 下面直接上代码,布局用的是Masonry

pragma mark - 1. 先看看效果哈

纯代码约束优先级.gif
pragma mark - 2. 代码实现加简单注释
#import "ViewController.h"
#import "Masonry.h"

@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]; //1.添加三个View UIView *orangeView = [[UIView alloc]init]; orangeView.backgroundColor = [UIColor orangeColor]; [self.view addSubview:orangeView]; self.orangeView = orangeView; //2. UIView *yellowView = [[UIView alloc]init]; yellowView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:yellowView]; self.yellowView = yellowView; //3. UIView *greenView = [[UIView alloc]init]; greenView.backgroundColor = [UIColor greenColor]; [self.view addSubview:greenView]; self.greenView = greenView; //配置约束 [self setUpRestrain]; } //配置约束 -(void)setUpRestrain { __weak typeof( self) weakSelf = self; #对于橙色View只需正常设置约束就好 [self.orangeView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.height.mas_equalTo(100); make.left.offset(10); make.top.offset(50); }]; #黄色View只会发生一次变化,就多设一个优先级较低的约束就好 [self.yellowView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.height.mas_equalTo(100); make.left.equalTo(weakSelf.orangeView.mas_right).offset(20); make.top.offset(50); #当橙色View消失后,黄色View缺少左边约束,所以给其加一个优先级更低的左边约束。当第一个左边约束失效后,这个约束就起作用了 make.left.equalTo(weakSelf.view.mas_left).offset(20).priority(300); }]; #同理绿色View的低级约束就得设置两个 [self.greenView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.height.mas_equalTo(100); make.left.equalTo(weakSelf.yellowView.mas_right).offset(20); make.top.offset(50); make.left.equalTo(weakSelf.orangeView.mas_right).offset(20).priority(300); make.left.equalTo(weakSelf.view.mas_left).offset(20).priority(250); }]; } //删除黄色View - (IBAction)cancelYellowBtn:(id)sender { #这里有个知识点:用约束布局实现动画,布局代码写在外面,然后调用强制布局方法写在UIView动画里面 [self.yellowView removeFromSuperview]; [UIView animateWithDuration:0.5 animations:^{ //强制刷新布局 [self.view layoutIfNeeded]; }]; } //删除橙色View - (IBAction)cancelGreenBtn:(id)sender { [self.orangeView removeFromSuperview]; [UIView animateWithDuration:0.5 animations:^{ //强制刷新布局 [self.view layoutIfNeeded]; }]; }

转载于:https://www.cnblogs.com/siasyl/p/6775055.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值