1
|
MagicNumber -> autoresizingMask -> autolayout |
以上是純手寫代碼所經歷的關于頁面布局的3個時期
在iphone1-iphone3gs時期 window的size固定為(320,480) 我們只需要簡單計算1下相對位置就行了
在iphone4-iphone4s時期 蘋果推出了retina屏 但是給了碼農們非常大的福利:window的size不變
在iphone5-iphone5s時期 window的size變了(320,568) 這時候autoresizingMask派上了用處(為啥這時候候不用Autolayout? 由于還要支持ios5唄) 簡單的適配1下便可
在iphone6+時期 window的width也產生了變化(相對5和5s的屏幕比例沒有變化) 終究是時候拋棄autoresizingMask改用autolayout了(不用支持ios5了 相對屏幕適配的多樣性來講autoresizingMask也已過時了)
那如何快速的上手autolayout呢? 說實話 當年ios6推出的同時新增了autolayout的特性 我看了1下官方文檔和demo 就立馬拋棄到1邊了 由于實在過于的繁瑣和啰嗦(有過經驗的朋友肯定有同感)
直到iPhone6發布以后 我知道使用autolayout勢在必行了 這時候想起了之前在閱讀Github看到過的1個第3方庫Masonry 在花了幾個小時的研究使用后 我就將autolayout掌握了(重點是我并沒有學習任何的官方文檔或其他的關于autolayout的知識) 這就是我為何要寫下這篇文章來推薦它的緣由.
介紹
Masonry 源碼:https://github.com/Masonry/Masonry
Masonry是1個輕量級的布局框架 具有自己的描寫語法 采取更優雅的鏈式語法封裝自動布局 簡潔明了 并具有高可讀性 而且同時支持 iOS 和 Max OS X。
我們先來看1段官方的sample code來認識1下Masonry
1
2
3
|
[view1 mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(superview). with .insets(padding); }]; |
看到block里面的那句話: make edges equalTo superview with insets
通過鏈式的自然語言 就把view1給autolayout好了 是否是簡單易懂?
使用
看1下Masonry支持哪1些屬性
1
2
3
4
5
6
7
8
9
10
11
|
@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; |
這些屬性與NSLayoutAttrubute的對比表以下
其中leading與left trailing與right 在正常情況下是等價的 但是當1些布局是從右至左時(比如阿拉伯文?沒有類似的經驗) 則會對調 換句話說就是基本可以不理不用 用left和right就行了
在ios8發布后 又新增了1堆奇奇怪怪的屬性(有興趣的朋友可以去瞅瞅) Masonry暫時還不支持(不過你要支持ios6,ios7 就沒必要去管那末多了)
在講實例之前 先介紹1個MACRO
1
|
#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self; |
快速的定義1個weakSelf 固然是用于block里面啦 下面進入正題(為了方便 我們測試的superView都是1個size為(300,300)的UIView)
下面 通過1些簡單的實例來簡單介紹如何輕松愉快的使用Masonry:
1. [基礎] 居中顯示1個view
1
2
3
4
5
6
7
8
9
10
11
12
13
|
上一篇 C#學習篇(一)泛型
下一篇 什么才算是真正的編程能力?