Masonry的實現原理

核心
是基於NSLayoutConstraint自動佈局來實現的

NSLayoutConstraint如何進行約束佈局?
1、要實現自動佈局,必須把該屬性設置爲NO
view.translatesAutoresizingMaskIntoConstraints = NO

2、然後使用 addConstraint添加約束

[self.view addConstraint:
[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1
constant:-10]];

而Masonry具體的實現呢?
1、MASViewConstraint定義具體的約束
2、鏈式調用實際上是在添加約束,通過代理(MASConstraintMaker)進行約束的添加,最後調用install爲視圖添加約束。
3、MASConstraintMaker的install最終還是會調用每個MASViewConstraint的install
MASViewConstraint的結構如下:

 

大致的過程
先執行block內的鏈式語法通過maker定義約束和添加到maker的約束數組裏面,最後再調用maker的install真正爲視圖添加約束,遍歷約束數組通過 [self.installedView addConstraint:layoutConstraint]添加約束

總結(摘抄自底下的參考博客,覺得高度概括了整個實現方案)
1.MASConstraintMaker作爲工廠,生產一個個MASViewConstraint約束對象。
2.MASViewConstraint和MASCompositeConstraint繼承於抽象類MASConstraint,爲我們提供了高度封裝的約束對象
3.View+MASAdditions這個UIView的擴展是Masonry與外界交互的接口類,這樣很好的把複雜的約束邏輯封裝在內部管理,又提供了簡單的API供用戶使用。

參考博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章