一個實現極為簡單的約束框架

<a name="table-content"></a>目錄

<a name="reason-for-this"></a> 起因

開發 iOS SDK 經常需要注意引入的開源代碼或者定義的類名和方法名,可能會和用戶代碼沖突。所以一般的做法是類名,類別方法名加前綴。

最近在開發 SDK 的時候需要寫一點界面,所以在思考用什么來布局。考慮使用 Masonry。但是引入 Masonry 需要對 Masonry 里面所有類、類別方法加前綴,成本太大,引入錯誤風險太高。同時 SDK 里面的界面通常比較簡單,數量也比較少,引入一個 Masonry 反而會增大編譯出來的二進制文件大小,不太值得。所以我就在思考如何設計一個代碼精簡的,類似 Masonry 的約束框架呢?

↑目錄

<a name="result-for-this"></a> 結果

在閱讀了 Masonry 的代碼之后,我決定仿照它來重新寫一個精簡的約束框架,這里的精簡是代碼量極少。所以就有了后面的 DLSimpleAutolayout。這個約束框架代碼總量大約只有300行。但是使用方式基本和 Masonry 類似,下面是 DLSimpleAutolayout 寫出來的布局代碼樣式。

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
@[
 view1.dl_top.equalTo(superview).offset(padding.top),
 view1.dl_left.equalTo(superview).offset(padding.left),
 view1.dl_bottom.equalTo(superview).offset(-padding.bottom),
 view1.dl_right.equalTo(superview).offset(-padding.right),
].dl_constraint_install();

↑目錄


<a name="how-to-encapsulate-autolayout"></a> 如何封裝 autolayout

下面我會循序漸進地講解為什么,以及如何封裝 autolayout

<a name="problem-about-original-api"></a> 使用原生約束 API 的問題

在 iOS 上面使用原生約束寫代碼是極為繁瑣的一件事。比如下面這樣的原生約束代碼(來自 Masonry README.md):

UIView *superview = self.view;

UIView *view1 = [[UIView alloc] init];
view1.translatesAutoresizingMaskIntoConstraints = NO;
view1.backgroundColor = [UIColor greenColor];
[superview addSubview:view1];

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);

[superview addConstraints:@[

    //view1 constraints
    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeTop
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeTop
                                multiplier:1.0
                                  constant:padding.top],

    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeLeft
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeLeft
                                multiplier:1.0
                                  constant:padding.left],

    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeBottom
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeBottom
                                multiplier:1.0
                                  constant:-padding.bottom],

    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeRight
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeRight
                                multiplier:1
                                  constant:-padding.right],

 ]];

問題出在蘋果提供的那個特別長的函數。當你的視圖多的時候,像上面這樣的代碼就會越來越龐大,可讀性也越來越低。

↑目錄

<a name="using-masonry"></a> 使用 Masonry

那么如何更加優雅的使用 autolayout 呢?絕大多數的 iOS 開發如果使用 autolayout 來布局視圖的話,肯定或多或少的聽說過 Masonry (如果是 Swift 版本的話,官方推薦 SnapKit)。

利用 Masonry,我們可以將上面約束代碼寫成下面這樣(來自 Masonry README.md):


UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler
    make.left.equalTo(superview.mas_left).with.offset(padding.left);
    make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom);
    make.right.equalTo(superview.mas_right).with.offset(-padding.right);
}];

Masonry 會幫助我們將約束添加到適當的視圖上(比如自身或者和另一個視圖的公共祖先),同時也會幫助我們設置相應視圖的 translatesAutoresizingMaskIntoConstraintsNO

↑目錄

<a name="using-dlsimpleautolayout"></a> 使用 DLSimpleAutolayout

DLSimpleAutolayout 是一個使用方式類似 Masonry 的約束框架,下面是 DLSimpleAutolayout 的約束代碼(等價于上面的 Masonry 代碼):

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
@[
 view1.dl_top.equalTo(superview).offset(padding.top),
 view1.dl_left.equalTo(superview).offset(padding.left),
 view1.dl_bottom.equalTo(superview).offset(-padding.bottom),
 view1.dl_right.equalTo(superview).offset(-padding.right),
].dl_constraint_install();

是不是看起來一摸一樣?!!

但是 DLSimpleAutolayout 的實現極為簡單,只有一個頭文件和一個實現文件,合計代碼行數只有300行左右。

↑目錄

<a name="how-to-implement-DLSimpleAutolayout"></a> DLSimpleAutolayout 實現原理

<a name="principle-autolayout"></a> 基本原理

首先你需要了解布局的基本原理

簡單的說每一個相等關系的約束最后會被 Apple 處理成一條類似下面的等式:

view1.left = 2.0 * view2.left + 8.0

上面這條公式的意思是 view1left 約束等于 view2left 值乘以 2 加 8。這里的 2 叫 multiplier,8 叫 constant,view1 叫 first item,view2 叫 second item,也就是分別對應

+(instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(nullable id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;

這個原生 API 的幾個參數。無論是 DLSimpleAutolayout 還是 Masonry 的實現,基本上都是對這個 API 的封裝,同時添加了一些其他代碼,方便使用者使用約束。

↑目錄

<a name="principle-DLSimpleViewAttribute"></a> DLSimpleAutolayout 的實現之 DLSimpleViewAttribute

DLSimpleAutolayout 的實現其實參考了 Masonry,比如 DLSimpleViewAttribute 類似與 MASViewAttributeDLSimpleViewAttribute 類型接口如下:


@interface DLSimpleViewAttribute : NSObject

@property (nonatomic, strong, readonly) DLSimpleViewAttribute *(^equalTo)(id view);
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *(^lessThanOrEqualTo)(id view);
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *(^greaterThanOrEqualTo)(id view);
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *(^multipliedBy)(CGFloat multipier);
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *(^offset)(CGFloat offset);
@property (nonatomic, strong, readonly) NSLayoutConstraint *(^install)();

@end

也就是對應約束的3種大小關系,同時可以對 constant 進行 offset 操作(對應設置 constant),對 second item 有 multipliedBy 操作(對應設置 multiplier),最后添加約束的時候需要手動 install() 。比如下面這樣:

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
view1.dl_top.equalTo(superview).offset(padding.top).install();
view1.dl_left.equalTo(superview).offset(padding.left).install();
view1.dl_bottom.equalTo(superview).offset(-padding.bottom).install();
view1.dl_right.equalTo(superview).offset(-padding.right).install();

當調用 install() 的時候,DLSimpleAutolayout 會根據當前配置的信息,來生成一個約束,同時將約束添加到自身或者是和 second item 的最近的公共視圖上。并設置自身的 translatesAutoresizingMaskIntoConstraintsNO。代碼如下所示:

- (NSLayoutConstraint * (^)())install {
    return ^id(){
        // 設置為 NO
        ((UIView *)self.firstItem).translatesAutoresizingMaskIntoConstraints = NO;
        NSLayoutConstraint *constaraint = [NSLayoutConstraint constraintWithItem:self.firstItem
                                                                       attribute:self.firstAttribute
                                                                       relatedBy:self.relation
                                                                          toItem:self.secondItem
                                                                       attribute:self.secondAttribute
                                                                      multiplier:self.multiplier
                                                                        constant:self.constant];
        if (self.secondItem == nil) {
            [self.firstItem addConstraint:constaraint];
        } else {
            // 尋找最近的公共祖先
            UIView *closestCommonSuperview = [self dl_ClosestCommonSuperview:self.firstItem view2:self.secondItem];
            [closestCommonSuperview addConstraint:constaraint];
        }
        return constaraint;
    };
}

↑目錄

<a name="principle-NSArray-category"></a> DLSimpleAutolayout 的實現之 NSArray 類別

考慮到方便在每個屬性后面自動使用 install(),我對 NSArray 添加了一個類別,封裝了這個操作。所以無需在每個 DLSimpleViewAttribute 對象后調用 install(),只需要將這些對象放到一個 NSArray 里面,對這個 array 調用 dl_constraint_install() 即可。這種類似語法糖的寫法也方便了使用者更好的組織、調整自己的布局代碼。

該 NSArray 類別公開接口如下:

@interface NSArray (DLSimpleAutoLayout)

@property (nonatomic, strong, readonly) NSArray<NSLayoutConstraint *> * (^dl_constraint_install)();

@end

寫出來的代碼類似下面這樣:

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
@[
 view1.dl_top.equalTo(superview).offset(padding.top),
 view1.dl_left.equalTo(superview).offset(padding.left),
 view1.dl_bottom.equalTo(superview).offset(-padding.bottom),
 view1.dl_right.equalTo(superview).offset(-padding.right),
].dl_constraint_install();

↑目錄

<a name="principle-UIView-category"></a> DLSimpleAutolayout 的實現之 UIView 類別

DLSimpleAutolayoutUIView 添加了類別,就是類似 dl_xxx 這樣的只讀屬性。
并且每個 view 返回的 dl_xxx 都是一個 DLSimpleViewAttribute 類型。該類別的接口如下:


@interface UIView (DLSimpleAutoLayout)

@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_left;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_top;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_right;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_bottom;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_leading;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_trailing;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_width;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_height;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_centerX;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_centerY;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_baseline;

#if TARGET_OS_IPHONE || TARGET_OS_TV

@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_leftMargin;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_rightMargin;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_topMargin;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_bottomMargin;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_leadingMargin;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_trailingMargin;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_centerXWithinMargins;
@property (nonatomic, strong, readonly) DLSimpleViewAttribute *dl_centerYWithinMargins;

#endif
@end

↑目錄

到此為止,DLSimpleAutolayout 基本上就實現了。具體實現的話可以看代碼 DLSimpleAutolayout


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

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,229評論 4 61
  • 銷售思維和營銷思維做外貿 雖然沒趕上外貿老前輩在黃金時代躺著賺錢的時代,好歹也在白銀時代混跡外貿圈十年,看著整個外...
    湯米蘇閱讀 164評論 0 0
  • 我不是詩人,但我會用心去寫一些文字,為你,為那個與我在靈魂里相遇,相知,相愛,相惜的人。你來,在我的眼里,你不來,...
    安俊杰閱讀 390評論 0 1