AotuLyout自動布局

都說一個合格的程序員應該有自己的博客,一直都比較懶,也沒學什么東西所以沒寫。正好最近加班,沒事就寫一些自己用的東西。

作為一個iOS開發程序員來說,離不開寫界面,那肯定得做屏幕適配。那么,肯定離不開自動布局的工具(當然,也有哥們全部控件的位置大小是根據屏幕寬高來算的,小弟我佩服)。自動布局的框架很多,都是對iOS原生的進行了一層封裝而已,大同小異。SDAutoLayout、Masonry、Purelayout等等,我今天將我自己目前用的Purelayout。

源碼解析

PureLayout 頭文件就不說了?

1、PureLayoutDefines.h

PureLayoutDefines.h這個類是對原生布局枚舉的命名轉換,相當于適配器。以及一些宏定義。

2、ALView+PureLayout.h

這個類將是我們主要使用的類,ALView 就是UIView,

#? define ALView? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? UIView

對視圖進行布局嘛,當然要建一個UIView的分類咯,這個類也是我們主要使用的類了。我們來看看它的方法:

+ (instancetype)newAutoLayoutView;

- (instancetype)initForAutoLayout;

- (instancetype)configureForAutoLayout;

用法例子:

UIView *corView = [UIView newAutoLayoutView];

首先它有這幾個初始化的方式,其實就比我們常用的多一句:

view.translatesAutoresizingMaskIntoConstraints = NO;

用來禁止AutoresizingMask轉換成AutoLayout。


然后,我們來說一下它的布局方法:

- (NSLayoutConstraint *)autoPinEdgeToSuperviewEdge:(ALEdge)edge;

- (NSLayoutConstraint *)autoPinEdgeToSuperviewEdge:(ALEdge)edge withInset:(CGFloat)inset;

- (NSLayoutConstraint *)autoPinEdgeToSuperviewEdge:(ALEdge)edge withInset:(CGFloat)inset relation:(NSLayoutRelation)relation

這三個方法顧名思義,相對于父視圖布局。說到父視圖,一定要記得在創建視圖后馬上寫上addSubview,這樣才能相對父視圖布局。

edge: 這個參數是哪一邊

inset: 差多少

relation:關系,>=、=、<=

比如:

[lab autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:20 relation:NSLayoutRelationGreaterThanOrEqual];

意思就是lab的左邊距離父視圖大于等于20,優先等于,怎樣形象吧。


- (NSLayoutConstraint *)autoPinEdge:(ALEdge)edge toEdge:(ALEdge)toEdge ofView:(ALView *)otherView;

- (NSLayoutConstraint *)autoPinEdge:(ALEdge)edge toEdge:(ALEdge)toEdge ofView:(ALView *)otherView withOffset:(CGFloat)offset;

- (NSLayoutConstraint *)autoPinEdge:(ALEdge)edge toEdge:(ALEdge)toEdge ofView:(ALView *)otherView withOffset:(CGFloat)offset relation:(NSLayoutRelation)relation;

這三個方法就是相對某個視圖布局,我就不上示例代碼了。不會的同學自己去試試,會的同學不會看到這里。


- (NSLayoutConstraint *)autoAlignAxisToSuperviewAxis:(ALAxis)axis;

這個方法呢是跟父視圖的對齊方式,一般用ALAxisVertical(水平)、ALAxisHorizontal(豎直)

就是中心點的橫坐標x或者縱坐標y位于父視圖中心,當然還有跟其他視圖對齊方式的方法,自己去研究哈。


- (PL__NSArray_of(NSLayoutConstraint *) *)autoPinEdgesToSuperviewEdgesWithInsets:(ALEdgeInsets)insets;

- (PL__NSArray_of(NSLayoutConstraint *) *)autoPinEdgesToSuperviewEdgesWithInsets:(ALEdgeInsets)insets excludingEdge:(ALEdge)edge;

這倆方法意思是直接設置跟父視圖的內邊距。

excludingEdge:意思是排除哪一邊

3、NSLayoutConstraint+PureLayout.h

這個類我只說倆方法

- (void)autoInstall;

// 移除約束

- (void)autoRemove;

假如某條約束你想要更改或者去除就去調用吧。

當然假如你還想根據內容改變高度寬度,就應該他約束對象記錄下來,然后改變它的值。

最后給出一個小小的demo,別忘記升級xcode8哦!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容