Masonry约束

本文介绍如何使用Masonry库为iOS应用中的UIView添加自动布局约束。通过简单的代码示例,展示了如何实现视图的居中及尺寸设置,并强调了在添加约束前需将视图加入父视图的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 @property (nonatomic, strong, readonly) MASConstraint *left;         //左侧

 @property (nonatomic, strong, readonly) MASConstraint *top;        //上侧

 @property (nonatomic, strong, readonly) MASConstraint *right;      //右侧

@property (nonatomic, strong, readonly) MASConstraint *bottom;   //下侧

@property (nonatomic, strong, readonly) MASConstraint *leading;   //首部

@property (nonatomic, strong, readonly) MASConstraint *trailing;   //尾部

@property (nonatomic, strong, readonly) MASConstraint *width;     //宽

@property (nonatomic, strong, readonly) MASConstraint *height;    //高

@property (nonatomic, strong, readonly) MASConstraint *centerX;  //横向居中

@property (nonatomic, strong, readonly) MASConstraint *centerY;  //纵向居中

@property (nonatomic, strong, readonly) MASConstraint *baseline; //文本基线

**

  1. 属性有了,接着我们应该怎么在视图中添加约束呢,Masonry给我们提供了3个方法

**

//新增约束
 - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;

//更新约束
 - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;

//清楚之前的所有约束,只会保留最新的约束
 - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;

 合理的利用这个3个函数,基本上可以应对任何情况了
2.居中一个view

  // 防止block中的循环引用
    __weak typeof (self) weakSelf = self
  // 初始化一个View
  UIView *bgView = [[UIView alloc]init];
  bgView.backgroundColor = [UIColor redColor];
  [self.view addSubview:bgView];
  // 使用mas_makeConstraints添加约束
  [bgView mas_makeConstraints:^(MASConstraintMaker *make) {  
  make.center.equalTo(weakSelf.view);       
  make.size.mas_equalTo(CGSizeMake(200, 200));
    }];

是不是很简单,这里有一点要必须注意下,添加约束前必须要把view添加到视图上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值