Masonry自动布局详解一:基本用法
Masonry自動布局詳解一:基本用法
說到iOS自動布局,有很多的解決辦法。有的人使用xib/storyboard自動布局,也有人使用frame來適配。對于前者,筆者并不喜歡,也不支持。對于后者,更是麻煩,到處計算高度、寬度等,千萬大量代碼的冗余,對維護和開發的效率都很低。
筆者在這里介紹純代碼自動布局的第三方庫:Masonry。這個庫使用率相當高,在全世界都有大量的開發者在使用,其star數量也是相當高的。
支持原創,請閱讀原文
效果圖
本節詳解Masonry的基本用法,先看看效果圖:
我們這里要布局使這三個控件的高度一致,而綠色和紅色的控件高度和寬度相待。
核心代碼
看下代碼:
- (void)viewDidLoad {[super viewDidLoad];UIView *greenView = UIView.new;greenView.backgroundColor = UIColor.greenColor;greenView.layer.borderColor = UIColor.blackColor.CGColor;greenView.layer.borderWidth = 2;[self.view addSubview:greenView];UIView *redView = UIView.new;redView.backgroundColor = UIColor.redColor;redView.layer.borderColor = UIColor.blackColor.CGColor;redView.layer.borderWidth = 2;[self.view addSubview:redView];UIView *blueView = UIView.new;blueView.backgroundColor = UIColor.blueColor;blueView.layer.borderColor = UIColor.blackColor.CGColor;blueView.layer.borderWidth = 2;[self.view addSubview:blueView];// 使這三個控件等高CGFloat padding = 10;[greenView mas_makeConstraints:^(MASConstraintMaker *make) {make.top.mas_equalTo(padding);make.left.mas_equalTo(padding);make.right.mas_equalTo(redView.mas_left).offset(-padding);make.bottom.mas_equalTo(blueView.mas_top).offset(-padding);// 三個控件等高make.height.mas_equalTo(@[redView, blueView]);// 紅、綠這兩個控件等高make.width.mas_equalTo(redView);}];[redView mas_makeConstraints:^(MASConstraintMaker *make) {make.top.height.bottom.mas_equalTo(greenView);make.right.mas_equalTo(-padding);make.left.mas_equalTo(greenView.mas_right).offset(padding);}];[blueView mas_makeConstraints:^(MASConstraintMaker *make) {make.height.mas_equalTo(greenView);make.bottom.mas_equalTo(-padding);make.left.mas_equalTo(padding);make.right.mas_equalTo(-padding);}]; }講解
添加約束的方法是:mas_makeConstraints。我們可以看到,約束可以使用鏈式方式,使用方法很簡單,看起來像一句話。
看這句話:make.top.height.bottom.mas_equalTo(greenView),意思是:使我的頂部、高度和底部都與greenView的頂部、高度和底部相等。因此,只要greenView的約束添加好了,那么redView的頂部、高度和底部也就自動計算出來了。
大多時候,我們并不會將一句話完整地寫出來,而是使用簡寫的方式。如:
make.right.mas_equalTo(-padding);其完整寫法為:
make.right.mas_equalTo(bludView.superView.mas_right).offset(-padding);當我們是要與父控件相對約束時,可以省略掉父視圖。注意,并不是什么時候都可以省略,只有約束是同樣的才可以省略。比如,約束都是right才可以。如果是一個left一個是right,那么就不能省略了。
源代碼
大家可以到筆者的github下載源代碼:https://github.com/CoderJackyHuang/MasonryDemo
溫馨提示:本節所講內容對應于BasicController中的內容
關注我
微信公眾號:iOSDevShares
有問必答QQ群:324400294
總結
以上是生活随笔為你收集整理的Masonry自动布局详解一:基本用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你真的了解实时计算吗?
- 下一篇: 简单的并发测试工具 ab.exe ab.