iOS - 使用"Masonry"库做约束(自动布局)

来源:互联网 发布:linux nobody 用户 编辑:程序博客网 时间:2024/06/06 13:10


之前做适配(还没接触过Masonry的时候) 大体有这样几种方案

第一种:

在pch文件写下

// 屏幕宽度

#define screenWidth [[UIScreen mainScreen]bounds].size.width


// 屏幕高度

#define screenHeight [[UIScreen mainScreen]bounds].size.height


之后就是根据页面大小还有比例来设计 


当我接触了Masonry 并且掌握之后 觉得真是方便很多

但是Masonry有一个缺点 控件之间的布局(x和y坐标)是相对的 但是大小是对于本身的 它不能获取到最后一个控件的frame值 只能知道大小

所以当你用scrollview的时候 判断内容大小的时候 这个控件的frame值就取不到了 

附上使用代码

 <span style="white-space:pre"></span>//图标        UIImageView * itemImage = [[UIImageView alloc]init];        itemImage.layer.cornerRadius = 20;        itemImage.image = [UIImage imageNamed:@"logo"];        itemImage.clipsToBounds = YES;        [self.contentView addSubview:itemImage];                //线        UIImageView * line = [[UIImageView alloc]init];        line.backgroundColor = MyColor(204, 174, 205);        [self.contentView addSubview:line];         [itemImage mas_makeConstraints:^(MASConstraintMaker *make) {                 make.left.equalTo(self.contentView).with.offset(50);            make.top.equalTo(self.contentView.mas_top).with.offset(20);            make.width.equalTo(@40);            make.height.equalTo(@40);        }];<span style="white-space:pre"></span>[line mas_makeConstraints:^(MASConstraintMaker *make) {                                make.left.equalTo(itemImage).with.offset(20.5);                make.top.equalTo(itemImage.mas_bottom).with.offset(5);                make.width.equalTo(@0.5);                make.height.equalTo(@30);                            }];


解析:

1⃣️

make.left.equalTo(self.contentView).with.offset(50);
表示控件的左边相等于<span style="font-family: Arial, Helvetica, sans-serif;">self.contentView的左边再加50个像素   </span>
</pre>2⃣️<p></p><p></p><pre name="code" class="objc">make.top.equalTo(self.contentView.mas_top).with.offset(20);
表示:控件的顶部距离self.contentView的顶部 (当方向相同其实可以省略方向)再加20

3⃣️:

make.width.equalTo(@40);
控件的宽度为40

4⃣️

make.height.equalTo(@30);
控件的高度为30


注意:

约束条件的中的宽度若不写 则会自动算出Label中字符串的长度做自适应

0 0
原创粉丝点击