Masonry1.1.0簡(jiǎn)單分析

Masonry介紹

Masonry是一個(gè)對(duì)系統(tǒng)NSLayoutConstraint進(jìn)行封裝的第三方自動(dòng)布局框架,采用鏈?zhǔn)骄幊痰姆绞教峁┙o開發(fā)者API。系統(tǒng)AutoLayout支持的操作,Masonry都支持,相比系統(tǒng)API功能來(lái)說(shuō),Masonry是有過(guò)之而無(wú)不及。

Masonry框架的基本結(jié)構(gòu)

Masonry文件結(jié)構(gòu)圖

首先我們看Masonry.h文件

#import <Foundation/Foundation.h>

//! Project version number for Masonry.
FOUNDATION_EXPORT double MasonryVersionNumber;

//! Project version string for Masonry.
FOUNDATION_EXPORT const unsigned char MasonryVersionString[];

#import "MASUtilities.h"
#import "View+MASAdditions.h"
#import "View+MASShorthandAdditions.h"
#import "ViewController+MASAdditions.h"
#import "NSArray+MASAdditions.h"
#import "NSArray+MASShorthandAdditions.h"
#import "MASConstraint.h"
#import "MASCompositeConstraint.h"
#import "MASViewAttribute.h"
#import "MASViewConstraint.h"
#import "MASConstraintMaker.h"
#import "MASLayoutConstraint.h"
#import "NSLayoutConstraint+MASDebugAdditions.h"

MASConstraint約束抽象類

MASCompositeConstraint試圖組合約束類

MASViewAttribute試圖屬性類,用于創(chuàng)建約束

MASViewConstraint試圖約束類,依賴于視圖屬性類

MASConstraintMaker創(chuàng)建約束的工廠方法

MASLayoutConstraint約束屬性,對(duì)NSLayoutConstraint的封裝

約束入口

我們都是對(duì)視圖進(jìn)行約束,所以入口就是一個(gè)UIView的分類 View+MASAdditions.h

/**
 *  following properties return a new MASViewAttribute with current view and appropriate NSLayoutAttribute
 */
@property (nonatomic, strong, readonly) MASViewAttribute *mas_left;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_top;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_right;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottom;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_leading;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailing;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_width;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_height;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerX;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerY;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_baseline;
@property (nonatomic, strong, readonly) MASViewAttribute *(^mas_attribute)(NSLayoutAttribute attr);

@property (nonatomic, strong, readonly) MASViewAttribute *mas_firstBaseline;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_lastBaseline;

#if TARGET_OS_IPHONE || TARGET_OS_TV

@property (nonatomic, strong, readonly) MASViewAttribute *mas_leftMargin;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_rightMargin;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_topMargin;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomMargin;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_leadingMargin;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailingMargin;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerXWithinMargins;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerYWithinMargins;

@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuide NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideLeading NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideTrailing NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideLeft NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideRight NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideTop NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideBottom NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideWidth NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideHeight NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideCenterX NS_AVAILABLE_IOS(11.0);
@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideCenterY NS_AVAILABLE_IOS(11.0);

#endif

這里,這些屬性返回一個(gè)當(dāng)前view的一個(gè)新的MASViewAttribute以及合適的NSLayoutAttribute。

MASViewAttribute這個(gè)對(duì)象是一個(gè)存儲(chǔ)視圖和相關(guān)NSLayoutAttribute的不可變?cè)M。描述約束方程左側(cè)或右側(cè)的一部分。

make構(gòu)建約束

/**
 *  Creates a MASConstraintMaker with the callee view.
 *  Any constraints defined are added to the view or the appropriate superview once the block has finished executing
 *
 *  @param block scope within which you can build up the constraints which you wish to apply to the view.
 *
 *  @return Array of created MASConstraints
 */
- (NSArray *)mas_makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;

該方法根據(jù)傳入的view創(chuàng)建一個(gè)MASConstraintMaker,一旦block結(jié)束執(zhí)行,任何定義的約束都被添加到view或者合適的superview上。返回值就是一個(gè)創(chuàng)建的MASConstraints數(shù)組。

update約束

/**
 *  Creates a MASConstraintMaker with the callee view.
 *  Any constraints defined are added to the view or the appropriate superview once the block has finished executing.
 *  If an existing constraint exists then it will be updated instead.
 *
 *  @param block scope within which you can build up the constraints which you wish to apply to the view.
 *
 *  @return Array of created/updated MASConstraints
 */
- (NSArray *)mas_updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;

該方法根據(jù)傳入的view創(chuàng)建一個(gè)MASConstraintMaker,一旦block結(jié)束執(zhí)行,任何定義的約束都被添加到view或者合適的superview上。如果一個(gè)約束存在,那么它會(huì)替代到本次更新的約束。返回值是一個(gè)創(chuàng)建的/更新的約束的數(shù)組。

remake約束

/**
 *  Creates a MASConstraintMaker with the callee view.
 *  Any constraints defined are added to the view or the appropriate superview once the block has finished executing.
 *  All constraints previously installed for the view will be removed.
 *
 *  @param block scope within which you can build up the constraints which you wish to apply to the view.
 *
 *  @return Array of created/updated MASConstraints
 */
- (NSArray *)mas_remakeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;

該方法用于根據(jù)傳入的view創(chuàng)建一個(gè)MASConstraintMaker,一旦block結(jié)束執(zhí)行,任何定義的約束都被添加到view或者合適的superview上。該view的所有以前的約束都將被remove掉,返回值是一個(gè)創(chuàng)建的/更新的約束的數(shù)組。該方法與update的區(qū)別是,update是更新相同的約束,而remake是完全刪除以前的約束,使用本次重新創(chuàng)建的約束。

MASConstraintMaker工廠類

這里MASConstraintMaker就是工廠方法,用于生成約束。具體負(fù)責(zé)創(chuàng)建MASConstraint類型的對(duì)象(依賴于MASConstraint接口,而不依賴于具體實(shí)現(xiàn))。mas_makeConstraints方法中的Block的參數(shù)就是MASConstraintMaker的對(duì)象。用戶可以通過(guò)該Block回調(diào)過(guò)來(lái)的MASConstraintMaker對(duì)象給View指定要添加的約束以及該約束的值。該工廠中的.m文件中的constraints屬性數(shù)組就記錄了該工廠創(chuàng)建的所有MASConstraint對(duì)象。

1.MASAttribute枚舉

typedef NS_OPTIONS(NSInteger, MASAttribute) {
    MASAttributeLeft = 1 << NSLayoutAttributeLeft,
    MASAttributeRight = 1 << NSLayoutAttributeRight,
    MASAttributeTop = 1 << NSLayoutAttributeTop,
    MASAttributeBottom = 1 << NSLayoutAttributeBottom,
    MASAttributeLeading = 1 << NSLayoutAttributeLeading,
    MASAttributeTrailing = 1 << NSLayoutAttributeTrailing,
    MASAttributeWidth = 1 << NSLayoutAttributeWidth,
    MASAttributeHeight = 1 << NSLayoutAttributeHeight,
    MASAttributeCenterX = 1 << NSLayoutAttributeCenterX,
    MASAttributeCenterY = 1 << NSLayoutAttributeCenterY,
    MASAttributeBaseline = 1 << NSLayoutAttributeBaseline,

    MASAttributeFirstBaseline = 1 << NSLayoutAttributeFirstBaseline,
    MASAttributeLastBaseline = 1 << NSLayoutAttributeLastBaseline,
    
#if TARGET_OS_IPHONE || TARGET_OS_TV
    
    MASAttributeLeftMargin = 1 << NSLayoutAttributeLeftMargin,
    MASAttributeRightMargin = 1 << NSLayoutAttributeRightMargin,
    MASAttributeTopMargin = 1 << NSLayoutAttributeTopMargin,
    MASAttributeBottomMargin = 1 << NSLayoutAttributeBottomMargin,
    MASAttributeLeadingMargin = 1 << NSLayoutAttributeLeadingMargin,
    MASAttributeTrailingMargin = 1 << NSLayoutAttributeTrailingMargin,
    MASAttributeCenterXWithinMargins = 1 << NSLayoutAttributeCenterXWithinMargins,
    MASAttributeCenterYWithinMargins = 1 << NSLayoutAttributeCenterYWithinMargins,

#endif
    
};

該枚舉其實(shí)就是對(duì)NSLayoutAttribute枚舉的一種封裝。

MASConstraint屬性

  1. 布局屬性定義
/**
 *  The following properties return a new MASViewConstraint
 *  with the first item set to the makers associated view and the appropriate MASViewAttribute
 */
@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;

@property (nonatomic, strong, readonly) MASConstraint *firstBaseline;
@property (nonatomic, strong, readonly) MASConstraint *lastBaseline;

#if TARGET_OS_IPHONE || TARGET_OS_TV

@property (nonatomic, strong, readonly) MASConstraint *leftMargin;
@property (nonatomic, strong, readonly) MASConstraint *rightMargin;
@property (nonatomic, strong, readonly) MASConstraint *topMargin;
@property (nonatomic, strong, readonly) MASConstraint *bottomMargin;
@property (nonatomic, strong, readonly) MASConstraint *leadingMargin;
@property (nonatomic, strong, readonly) MASConstraint *trailingMargin;
@property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins;
@property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins;

#endif

下面就以left屬性為例看一下實(shí)現(xiàn)。

- (MASConstraint *)left {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft];
}
- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute];
}

這里,不管是left還是right或者center都會(huì)調(diào)用方法- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute,然后就是添加約束。這里依賴了兩個(gè)類,分別是MASViewAttribute和MASViewConstraint。

主要看一下下面這個(gè)方法,這個(gè)走的MASConstraint+Private.h文件中的代理MASConstraintDelegate,該代理中有兩個(gè)方法。

@protocol MASConstraintDelegate <NSObject>

/**
 *  Notifies the delegate when the constraint needs to be replaced with another constraint. For example
 *  A MASViewConstraint may turn into a MASCompositeConstraint when an array is passed to one of the equality blocks
 */
- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint;

- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute;

@end

maker工廠方法中都實(shí)現(xiàn)了這個(gè)代理方法。

//代理方法實(shí)現(xiàn)
- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint {
    NSUInteger index = [self.constraints indexOfObject:constraint];
    NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint);
    [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint];
}

- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    //實(shí)例化MASViewAttribute
    MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute];
    //實(shí)例化MASViewConstraint
    MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute];    //判斷傳入的參數(shù)是不是MASViewConstraint類型,如果是進(jìn)入if分支
    if ([constraint isKindOfClass:MASViewConstraint.class]) {
        //replace with composite constraint
        NSArray *children = @[constraint, newConstraint];  
        //MASCompositeConstraint實(shí)例化并設(shè)置代理
        MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children];
        compositeConstraint.delegate = self;
        //調(diào)用代理方法進(jìn)行約束替換
        [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint];
        return compositeConstraint;
    }
    //如果constraint為nil,那么就設(shè)置代理,并將新的約束添加到屬性數(shù)組constraints里面
    if (!constraint) {
        newConstraint.delegate = self;
        [self.constraints addObject:newConstraint];
    }
    return newConstraint;
}

這里需要說(shuō)明MASViewConstraintMASConstraint的子類。通過(guò)NSLayoutAttribute創(chuàng)建一個(gè)MASConstraint并將創(chuàng)建的約束加入到數(shù)組constraints中,如果設(shè)置的是size、center等復(fù)合型的約束,則創(chuàng)建包含多個(gè)子約束的MASCompositeConstraint

  1. block
/**
 *  Returns a block which creates a new MASCompositeConstraint with the first item set
 *  to the makers associated view and children corresponding to the set bits in the
 *  MASAttribute parameter. Combine multiple attributes via binary-or.
 */
@property (nonatomic, strong, readonly) MASConstraint *(^attributes)(MASAttribute attrs);

該只讀屬性返回一個(gè)block,該塊使用第一個(gè)item集創(chuàng)建新的MASCompositeConstraint與makers關(guān)聯(lián)的視圖和與MASAttribute參數(shù)中的設(shè)置位對(duì)應(yīng)的子項(xiàng)。 通過(guò)binary-or組合多個(gè)屬性。

//該block是一個(gè)帶參數(shù)和帶返回值的block,傳入的是MASAttribute類型的參數(shù)返回的是MASConstraint,最后都是調(diào)用下面方法進(jìn)行具體的實(shí)現(xiàn)。
- (MASConstraint *(^)(MASAttribute))attributes {
    return ^(MASAttribute attrs){
        return [self addConstraintWithAttributes:attrs];
    };
}

- (MASConstraint *)addConstraintWithAttributes:(MASAttribute)attrs {
    // 這里是列舉出所有可能的MASAttribute類型的布局
    __unused MASAttribute anyAttribute = (MASAttributeLeft | MASAttributeRight | MASAttributeTop | MASAttributeBottom | MASAttributeLeading
                                          | MASAttributeTrailing | MASAttributeWidth | MASAttributeHeight | MASAttributeCenterX
                                          | MASAttributeCenterY | MASAttributeBaseline
                                          | MASAttributeFirstBaseline | MASAttributeLastBaseline
#if TARGET_OS_IPHONE || TARGET_OS_TV
                                          | MASAttributeLeftMargin | MASAttributeRightMargin | MASAttributeTopMargin | MASAttributeBottomMargin
                                          | MASAttributeLeadingMargin | MASAttributeTrailingMargin | MASAttributeCenterXWithinMargins
                                          | MASAttributeCenterYWithinMargins
#endif
                                          );
    
     //斷言,如果傳入的布局參數(shù)不再上面列舉出的布局類型中就拋出異常
    NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)");
    
    //定義一個(gè)可變數(shù)據(jù),并判斷attrs的類型,并將相應(yīng)的布局添加到可變數(shù)組中
    NSMutableArray *attributes = [NSMutableArray array];
    
    if (attrs & MASAttributeLeft) [attributes addObject:self.view.mas_left];
    if (attrs & MASAttributeRight) [attributes addObject:self.view.mas_right];
    if (attrs & MASAttributeTop) [attributes addObject:self.view.mas_top];
    if (attrs & MASAttributeBottom) [attributes addObject:self.view.mas_bottom];
    if (attrs & MASAttributeLeading) [attributes addObject:self.view.mas_leading];
    if (attrs & MASAttributeTrailing) [attributes addObject:self.view.mas_trailing];
    if (attrs & MASAttributeWidth) [attributes addObject:self.view.mas_width];
    if (attrs & MASAttributeHeight) [attributes addObject:self.view.mas_height];
    if (attrs & MASAttributeCenterX) [attributes addObject:self.view.mas_centerX];
    if (attrs & MASAttributeCenterY) [attributes addObject:self.view.mas_centerY];
    if (attrs & MASAttributeBaseline) [attributes addObject:self.view.mas_baseline];
    if (attrs & MASAttributeFirstBaseline) [attributes addObject:self.view.mas_firstBaseline];
    if (attrs & MASAttributeLastBaseline) [attributes addObject:self.view.mas_lastBaseline];
    
#if TARGET_OS_IPHONE || TARGET_OS_TV
    
    if (attrs & MASAttributeLeftMargin) [attributes addObject:self.view.mas_leftMargin];
    if (attrs & MASAttributeRightMargin) [attributes addObject:self.view.mas_rightMargin];
    if (attrs & MASAttributeTopMargin) [attributes addObject:self.view.mas_topMargin];
    if (attrs & MASAttributeBottomMargin) [attributes addObject:self.view.mas_bottomMargin];
    if (attrs & MASAttributeLeadingMargin) [attributes addObject:self.view.mas_leadingMargin];
    if (attrs & MASAttributeTrailingMargin) [attributes addObject:self.view.mas_trailingMargin];
    if (attrs & MASAttributeCenterXWithinMargins) [attributes addObject:self.view.mas_centerXWithinMargins];
    if (attrs & MASAttributeCenterYWithinMargins) [attributes addObject:self.view.mas_centerYWithinMargins];
    
#endif
    
    // 定義另外一個(gè)局部可變數(shù)組
    NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count];
    
    //遍歷上面的attributes可變數(shù)組,用其中的元素實(shí)例化MASViewConstraint對(duì)象并添加到新的children數(shù)組中
    for (MASViewAttribute *a in attributes) {
        [children addObject:[[MASViewConstraint alloc] initWithFirstViewAttribute:a]];
    }
    
    //根據(jù)數(shù)組children實(shí)例化MASCompositeConstraint對(duì)象,并作為返回值返回
    MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children];
    constraint.delegate = self;
    [self.constraints addObject:constraint];
    return constraint;
}
  1. edges、size和center
/**
 *  Creates a MASCompositeConstraint with type MASCompositeConstraintTypeEdges
 *  which generates the appropriate MASViewConstraint children (top, left, bottom, right)
 *  with the first item set to the makers associated view
 */
@property (nonatomic, strong, readonly) MASConstraint *edges;

/**
 *  Creates a MASCompositeConstraint with type MASCompositeConstraintTypeSize
 *  which generates the appropriate MASViewConstraint children (width, height)
 *  with the first item set to the makers associated view
 */
@property (nonatomic, strong, readonly) MASConstraint *size;

/**
 *  Creates a MASCompositeConstraint with type MASCompositeConstraintTypeCenter
 *  which generates the appropriate MASViewConstraint children (centerX, centerY)
 *  with the first item set to the makers associated view
 */
@property (nonatomic, strong, readonly) MASConstraint *center;

edges:根據(jù)MASCompositeConstraintTypeEdges類型創(chuàng)建一個(gè)MASCompositeConstraint對(duì)象,產(chǎn)生適合的MASViewConstraint子對(duì)象 (top, left, bottom, right)

size:根據(jù)MASCompositeConstraintTypeSize類型創(chuàng)建一個(gè)MASCompositeConstraint對(duì)象,產(chǎn)生適合的MASViewConstraint子對(duì)象 (width, height)

center:根據(jù)MASCompositeConstraintTypeCenter類型創(chuàng)建一個(gè)MASCompositeConstraint對(duì)象,產(chǎn)生適合的MASViewConstraint子對(duì)象 (centerX, centerY)

  1. updateExisting、removeExisting
/**
 *  Whether or not to check for an existing constraint instead of adding constraint
 *  是否去檢查一個(gè)存在的約束,而不是添加約束
 */
@property (nonatomic, assign) BOOL updateExisting;

/**
 *  Whether or not to remove existing constraints prior to installing
 *  在安裝約束前是否移除約束
 */
@property (nonatomic, assign) BOOL removeExisting;

下面我們看一下在maker工廠方法中的使用,如下所示:

- (NSArray *)install {
    if (self.removeExisting) {
        //取出當(dāng)前view安裝的所有約束,并調(diào)用uninstall方法卸載約束。
        NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view];
        for (MASConstraint *constraint in installedConstraints) {
            [constraint uninstall];
        }
    }
    NSArray *constraints = self.constraints.copy;
    for (MASConstraint *constraint in constraints) {
        constraint.updateExisting = self.updateExisting;
        [constraint install];
    }
    [self.constraints removeAllObjects];
    return constraints;
}

在maker工廠方法里面,遍歷屬性數(shù)組self.constraints,并調(diào)用MASConstraint的install方法安裝約束。在將設(shè)置好添加到constraints數(shù)組中的約束都設(shè)置好后就要開始把約束加到View上起作用,方法為install,邏輯如下:

如果是remake,也就是removeExisting =YES時(shí),將已經(jīng)添加上的約束全部uninstall,把本次maker里的所有創(chuàng)建的contraint設(shè)置好updateExisting,然后一個(gè)一個(gè)的install。

//MASConstraint.m文件中
- (void)install { MASMethodNotImplemented(); }

- (void)uninstall { MASMethodNotImplemented(); }

#define MASMethodNotImplemented() \
    @throw [NSException exceptionWithName:NSInternalInconsistencyException \
                                   reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \
                                 userInfo:nil]
  1. group合并約束
    該方法可以將多個(gè)maker中的多個(gè)約束合并為一個(gè)約束。
- (MASConstraint * (^)(dispatch_block_t))group;

//實(shí)現(xiàn)方法
- (MASConstraint *(^)(dispatch_block_t group))group {
    return ^id(dispatch_block_t group) {
        NSInteger previousCount = self.constraints.count;
        group();

        NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)];
        MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children];
        constraint.delegate = self;
        return constraint;
    };
}

MASConstraint類解析

首先MASConstraint作為約束,是MASViewConstraint和MASCompositeConstraint的父類,其中MASViewConstraint指單個(gè)約束,而MASCompositeConstraint指復(fù)合約束。

#import "MASUtilities.h"

/**
 *  Enables Constraints to be created with chainable syntax
 *  Constraint can represent single NSLayoutConstraint (MASViewConstraint) 
 *  or a group of NSLayoutConstraints (MASComposisteConstraint)
 */
@interface MASConstraint : NSObject

// Chaining Support

/**
 *  Modifies the NSLayoutConstraint constant,
 *  only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following
 *  NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight
 *  修改NSLayoutConstraint常數(shù),僅僅影響第一個(gè)item的NSLayoutAttribute
 *  NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight之一的MASConstraints
 */
- (MASConstraint * (^)(MASEdgeInsets insets))insets;

/**
 *  Modifies the NSLayoutConstraint constant,
 *  only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following
 *  NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight
 *  修改NSLayoutConstraint常數(shù),僅僅影響第一個(gè)item的NSLayoutAttribute
 *  NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight之一的MASConstraints
 */
- (MASConstraint * (^)(CGFloat inset))inset;

/**
 *  Modifies the NSLayoutConstraint constant,
 *  only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following
 *  NSLayoutAttributeWidth, NSLayoutAttributeHeight
 *  修改NSLayoutConstraint常數(shù),僅僅影響第一個(gè)item的NSLayoutAttribute
 *  NSLayoutAttributeWidth, NSLayoutAttributeHeight 之一的MASConstraints
 */
- (MASConstraint * (^)(CGSize offset))sizeOffset;

/**
 *  Modifies the NSLayoutConstraint constant,
 *  only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following
 *  NSLayoutAttributeCenterX, NSLayoutAttributeCenterY
 *  修改NSLayoutConstraint常數(shù),僅僅影響第一個(gè)item的NSLayoutAttribute
 *  NSLayoutAttributeCenterX, NSLayoutAttributeCenterY 之一的MASConstrain
 */
- (MASConstraint * (^)(CGPoint offset))centerOffset;

/**
 *  Modifies the NSLayoutConstraint constant
 *  修改NSLayoutConstraint常數(shù)
 */
- (MASConstraint * (^)(CGFloat offset))offset;

/**
 *  Modifies the NSLayoutConstraint constant based on a value type
 *  基于值類型,修改NSLayoutConstraint常數(shù)
 */
- (MASConstraint * (^)(NSValue *value))valueOffset;

/**
 *  Sets the NSLayoutConstraint multiplier property
 */
- (MASConstraint * (^)(CGFloat multiplier))multipliedBy;

/**
 *  Sets the NSLayoutConstraint multiplier to 1.0/dividedBy
 */
- (MASConstraint * (^)(CGFloat divider))dividedBy;

/**
 *  Sets the NSLayoutConstraint priority to a float or MASLayoutPriority
 */
- (MASConstraint * (^)(MASLayoutPriority priority))priority;

/**
 *  Sets the NSLayoutConstraint priority to MASLayoutPriorityLow
 */
- (MASConstraint * (^)(void))priorityLow;

/**
 *  Sets the NSLayoutConstraint priority to MASLayoutPriorityMedium
 */
- (MASConstraint * (^)(void))priorityMedium;

/**
 *  Sets the NSLayoutConstraint priority to MASLayoutPriorityHigh
 */
- (MASConstraint * (^)(void))priorityHigh;

/**
 *  Sets the constraint relation to NSLayoutRelationEqual
 *  returns a block which accepts one of the following:
 *    MASViewAttribute, UIView, NSValue, NSArray
 *  see readme for more details.
 */
- (MASConstraint * (^)(id attr))equalTo;

/**
 *  Sets the constraint relation to NSLayoutRelationGreaterThanOrEqual
 *  returns a block which accepts one of the following:
 *    MASViewAttribute, UIView, NSValue, NSArray
 *  see readme for more details.
 */
- (MASConstraint * (^)(id attr))greaterThanOrEqualTo;

/**
 *  Sets the constraint relation to NSLayoutRelationLessThanOrEqual
 *  returns a block which accepts one of the following:
 *    MASViewAttribute, UIView, NSValue, NSArray
 *  see readme for more details.
 */
- (MASConstraint * (^)(id attr))lessThanOrEqualTo;

/**
 *  Optional semantic property which has no effect but improves the readability of constraint
 */
- (MASConstraint *)with;

/**
 *  Optional semantic property which has no effect but improves the readability of constraint
 */
- (MASConstraint *)and;

/**
 *  Creates a new MASCompositeConstraint with the called attribute and reciever
 */
- (MASConstraint *)left;
- (MASConstraint *)top;
- (MASConstraint *)right;
- (MASConstraint *)bottom;
- (MASConstraint *)leading;
- (MASConstraint *)trailing;
- (MASConstraint *)width;
- (MASConstraint *)height;
- (MASConstraint *)centerX;
- (MASConstraint *)centerY;
- (MASConstraint *)baseline;

- (MASConstraint *)firstBaseline;
- (MASConstraint *)lastBaseline;

#if TARGET_OS_IPHONE || TARGET_OS_TV

- (MASConstraint *)leftMargin;
- (MASConstraint *)rightMargin;
- (MASConstraint *)topMargin;
- (MASConstraint *)bottomMargin;
- (MASConstraint *)leadingMargin;
- (MASConstraint *)trailingMargin;
- (MASConstraint *)centerXWithinMargins;
- (MASConstraint *)centerYWithinMargins;

#endif

......省略

@end

1. 鏈?zhǔn)街С?/h4>
#define MASEdgeInsets UIEdgeInsets

//MASConstraint.h
- (MASConstraint * (^)(MASEdgeInsets insets))insets;

//MASConstraint.m
- (MASConstraint * (^)(MASEdgeInsets))insets {
    return ^id(MASEdgeInsets insets){
        self.insets = insets;
        return self;
    };
}

//這是一個(gè)抽象方法,在MASConstraint類中沒有實(shí)現(xiàn)
- (void)setInsets:(MASEdgeInsets __unused)insets { MASMethodNotImplemented(); }

#define MASMethodNotImplemented() \
    @throw [NSException exceptionWithName:NSInternalInconsistencyException \
                                   reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \
                                 userInfo:nil]

首先更新一下屬性self.insets,然后把自己self返回去。還記得工廠方法里面的maker嗎?它就會(huì)返回一個(gè)MASConstraint對(duì)象,這里我們調(diào)用上面的block然后就將自己返回去,你就可以一直用點(diǎn)語(yǔ)法install約束,這就是鏈?zhǔn)骄幊獭?/p>

2.NSLayoutConstraint常數(shù)設(shè)置

MASConstraint的子類MASCompositeConstraint和MASViewConstraint中都進(jìn)行了重寫并實(shí)現(xiàn)。

//MASCompositeConstraint.m
- (void)setInsets:(MASEdgeInsets)insets {
    for (MASConstraint *constraint in self.childConstraints) {
        constraint.insets = insets;
    }
}

//MASViewConstraint.m
- (void)setInsets:(MASEdgeInsets)insets {
    NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute;
    switch (layoutAttribute) {
        case NSLayoutAttributeLeft:
        case NSLayoutAttributeLeading:
            self.layoutConstant = insets.left;
            break;
        case NSLayoutAttributeTop:
            self.layoutConstant = insets.top;
            break;
        case NSLayoutAttributeBottom:
            self.layoutConstant = -insets.bottom;
            break;
        case NSLayoutAttributeRight:
        case NSLayoutAttributeTrailing:
            self.layoutConstant = -insets.right;
            break;
        default:
            break;
    }
}

都是用來(lái)進(jìn)行更改約束的。

3.NSLayoutConstraint Installation支持

/**
 *  Activates an NSLayoutConstraint if it's supported by an OS. 
 *  Invokes install otherwise.
 *  如果OS支持就激活一個(gè)NSLayoutConstraint,否則就調(diào)用install
 */
- (void)activate;

/**
 *  Deactivates previously installed/activated NSLayoutConstraint.
 *  銷毀前面安裝或者激活的NSLayoutConstraint
 */
- (void)deactivate;

/**
 *  Creates a NSLayoutConstraint and adds it to the appropriate view.
 *  創(chuàng)建一個(gè)NSLayoutConstraint并將它添加到合適的view上
 */
- (void)install;

/**
 *  Removes previously installed NSLayoutConstraint
 *  移除以前安裝的NSLayoutConstraint
 */
- (void)uninstall;


//MASConstraint.m
- (void)activate { MASMethodNotImplemented(); }

- (void)deactivate { MASMethodNotImplemented(); }

- (void)install { MASMethodNotImplemented(); }

- (void)uninstall { MASMethodNotImplemented(); }

這四個(gè)方法都是抽象方法,均不在給類中實(shí)現(xiàn),而是在子類MASCompositeConstraint和MASViewConstraint中都進(jìn)行了重寫并實(shí)現(xiàn)。

下面看一下在子類中的實(shí)現(xiàn)情況。

//MASCompositeConstraint.m
- (void)activate {
    for (MASConstraint *constraint in self.childConstraints) {
        [constraint activate];
    }
}

- (void)deactivate {
    for (MASConstraint *constraint in self.childConstraints) {
        [constraint deactivate];
    }
}

- (void)install {
    for (MASConstraint *constraint in self.childConstraints) {
        constraint.updateExisting = self.updateExisting;
        [constraint install];
    }
}

- (void)uninstall {
    for (MASConstraint *constraint in self.childConstraints) {
        [constraint uninstall];
    }
}


//MASViewConstraint.m
   [self install];
}

- (void)deactivate {
    [self uninstall];
}

- (void)install {
    if (self.hasBeenInstalled) {
        return;
    }
    
    if ([self supportsActiveProperty] && self.layoutConstraint) {
        self.layoutConstraint.active = YES;
        [self.firstViewAttribute.view.mas_installedConstraints addObject:self];
        return;
    }
    
    MAS_VIEW *firstLayoutItem = self.firstViewAttribute.item;
    NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute;
    MAS_VIEW *secondLayoutItem = self.secondViewAttribute.item;
    NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute;

    // alignment attributes must have a secondViewAttribute
    // therefore we assume that is refering to superview
    // eg make.left.equalTo(@10)
    if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) {
        secondLayoutItem = self.firstViewAttribute.view.superview;
        secondLayoutAttribute = firstLayoutAttribute;
    }
    
    MASLayoutConstraint *layoutConstraint
        = [MASLayoutConstraint constraintWithItem:firstLayoutItem
                                        attribute:firstLayoutAttribute
                                        relatedBy:self.layoutRelation
                                           toItem:secondLayoutItem
                                        attribute:secondLayoutAttribute
                                       multiplier:self.layoutMultiplier
                                         constant:self.layoutConstant];
    
    layoutConstraint.priority = self.layoutPriority;
    layoutConstraint.mas_key = self.mas_key;
    
    if (self.secondViewAttribute.view) {
        MAS_VIEW *closestCommonSuperview = [self.firstViewAttribute.view mas_closestCommonSuperview:self.secondViewAttribute.view];
        NSAssert(closestCommonSuperview,
                 @"couldn't find a common superview for %@ and %@",
                 self.firstViewAttribute.view, self.secondViewAttribute.view);
        self.installedView = closestCommonSuperview;
    } else if (self.firstViewAttribute.isSizeAttribute) {
        self.installedView = self.firstViewAttribute.view;
    } else {
        self.installedView = self.firstViewAttribute.view.superview;
    }


    MASLayoutConstraint *existingConstraint = nil;
    if (self.updateExisting) {
        existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint];
    }
    if (existingConstraint) {
        // just update the constant
        existingConstraint.constant = layoutConstraint.constant;
        self.layoutConstraint = existingConstraint;
    } else {
        [self.installedView addConstraint:layoutConstraint];
        self.layoutConstraint = layoutConstraint;
        [firstLayoutItem.mas_installedConstraints addObject:self];
    }
}

- (MASLayoutConstraint *)layoutConstraintSimilarTo:(MASLayoutConstraint *)layoutConstraint {
    // check if any constraints are the same apart from the only mutable property constant

    // go through constraints in reverse as we do not want to match auto-resizing or interface builder constraints
    // and they are likely to be added first.
    for (NSLayoutConstraint *existingConstraint in self.installedView.constraints.reverseObjectEnumerator) {
        if (![existingConstraint isKindOfClass:MASLayoutConstraint.class]) continue;
        if (existingConstraint.firstItem != layoutConstraint.firstItem) continue;
        if (existingConstraint.secondItem != layoutConstraint.secondItem) continue;
        if (existingConstraint.firstAttribute != layoutConstraint.firstAttribute) continue;
        if (existingConstraint.secondAttribute != layoutConstraint.secondAttribute) continue;
        if (existingConstraint.relation != layoutConstraint.relation) continue;
        if (existingConstraint.multiplier != layoutConstraint.multiplier) continue;
        if (existingConstraint.priority != layoutConstraint.priority) continue;

        return (id)existingConstraint;
    }
    return nil;
}

- (void)uninstall {
    if ([self supportsActiveProperty]) {
        self.layoutConstraint.active = NO;
        [self.firstViewAttribute.view.mas_installedConstraints removeObject:self];
        return;
    }
    
    [self.installedView removeConstraint:self.layoutConstraint];
    self.layoutConstraint = nil;
    self.installedView = nil;
    
    [self.firstViewAttribute.view.mas_installedConstraints removeObject:self];
}

4.MASConstraint分類

@interface MASConstraint (AutoboxingSupport)

/**
 *  Aliases to corresponding relation methods (for shorthand macros)
 *  Also needed to aid autocompletion
 */
- (MASConstraint * (^)(id attr))mas_equalTo;
- (MASConstraint * (^)(id attr))mas_greaterThanOrEqualTo;
- (MASConstraint * (^)(id attr))mas_lessThanOrEqualTo;

/**
 *  A dummy method to aid autocompletion
 */
- (MASConstraint * (^)(id offset))mas_offset;

@end

- (MASConstraint * (^)(id attr))mas_equalTo;為例進(jìn)行說(shuō)明

- (MASConstraint * (^)(id))mas_equalTo {
    return ^id(id attribute) {
        return self.equalToWithRelation(attribute, NSLayoutRelationEqual);
    };
}

- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { MASMethodNotImplemented(); }

可見,這個(gè)在本抽象類還是沒有實(shí)現(xiàn),在子類MASCompositeConstraint和MASViewConstraint中都進(jìn)行了重寫并實(shí)現(xiàn)。

//MASCompositeConstraint.m
- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation {
    return ^id(id attr, NSLayoutRelation relation) {
        for (MASConstraint *constraint in self.childConstraints.copy) {
            constraint.equalToWithRelation(attr, relation);
        }
        return self;
    };
}

//MASViewConstraint.m
- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation {
    return ^id(id attribute, NSLayoutRelation relation) {
        if ([attribute isKindOfClass:NSArray.class]) {
            NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation");
            NSMutableArray *children = NSMutableArray.new;
            for (id attr in attribute) {
                MASViewConstraint *viewConstraint = [self copy];
                viewConstraint.layoutRelation = relation;
                viewConstraint.secondViewAttribute = attr;
                [children addObject:viewConstraint];
            }
            MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children];
            compositeConstraint.delegate = self.delegate;
            [self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint];
            return compositeConstraint;
        } else {
            NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation");
            self.layoutRelation = relation;
            self.secondViewAttribute = attribute;
            return self;
        }
    };
}

MASCompositeConstraint類解析

#import "MASConstraint.h"
#import "MASUtilities.h"

/**
 *  A group of MASConstraint objects
 */
@interface MASCompositeConstraint : MASConstraint

/**
 *  Creates a composite with a predefined array of children
 *
 *  @param  children    child MASConstraints
 *
 *  @return a composite constraint
 */
- (id)initWithChildren:(NSArray *)children;

@end

該類只有一個(gè)實(shí)例化方法,用于實(shí)例化對(duì)象,傳入的參數(shù)children,為約束數(shù)組,利用這個(gè)數(shù)組進(jìn)行合成約束。

在其.m中不僅實(shí)現(xiàn)了這個(gè)實(shí)例化方法,還重寫了很多MASConstrain方法。并設(shè)置代理和實(shí)現(xiàn)了MASConstraintDelegate。我們首先看一下這個(gè)實(shí)例化方法。

@property (nonatomic, strong) NSMutableArray *childConstraints;

- (id)initWithChildren:(NSArray *)children {
    self = [super init];
    if (!self) return nil;

    _childConstraints = [children mutableCopy];
    for (MASConstraint *constraint in _childConstraints) {
        constraint.delegate = self;
    }

    return self;
}

下面看一下內(nèi)部的組織結(jié)構(gòu),如下圖所示:

MASCompositeConstraint

從這我們就可以看到Masonry的組織結(jié)構(gòu)非常清爽,很多方法都在父類定義并在子類重寫,子類只保留了一個(gè)自定義的示例化方法。

MASViewConstraint類解析

該類是一個(gè)單約束,包含創(chuàng)建NSLayoutConstraint所需要的屬性,并將其添加到適合的view上.

/**
 *  A single constraint.
 *  Contains the attributes neccessary for creating a NSLayoutConstraint and adding it to the appropriate view
 *  NSLayoutConstraint的第一個(gè)item/view和第一個(gè)屬性
 */
@interface MASViewConstraint : MASConstraint <NSCopying>

/**
 *  First item/view and first attribute of the NSLayoutConstraint
 *  NSLayoutConstraint的第二個(gè)item/view和第二個(gè)屬性
 */
@property (nonatomic, strong, readonly) MASViewAttribute *firstViewAttribute;

/**
 *  Second item/view and second attribute of the NSLayoutConstraint
 */
@property (nonatomic, strong, readonly) MASViewAttribute *secondViewAttribute;

/**
 *  initialises the MASViewConstraint with the first part of the equation
 *
 *  @param  firstViewAttribute  view.mas_left, view.mas_width etc.
 *
 *  @return a new view constraint
 */
- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute;

/**
 *  Returns all MASViewConstraints installed with this view as a first item.
 *
 *  @param  view  A view to retrieve constraints for.
 *
 *  @return An array of MASViewConstraints.
 */
+ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view;

@end
  1. 實(shí)例化方法
@property (nonatomic, assign) MASLayoutPriority layoutPriority;
@property (nonatomic, assign) CGFloat layoutMultiplier;


- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute {
    self = [super init];
    if (!self) return nil;
    
    _firstViewAttribute = firstViewAttribute;
    self.layoutPriority = MASLayoutPriorityRequired;
    self.layoutMultiplier = 1;
    
    return self;
}
  1. 返回所有安裝的約束
+ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view {
    return [view.mas_installedConstraints allObjects];
}

這里要用到一個(gè)MAS_VIEW(其實(shí)就是UIView)的一個(gè)分類。

@interface MAS_VIEW (MASConstraints)

@property (nonatomic, readonly) NSMutableSet *mas_installedConstraints;

@end

@implementation MAS_VIEW (MASConstraints)

static char kInstalledConstraintsKey;

- (NSMutableSet *)mas_installedConstraints {
    NSMutableSet *constraints = objc_getAssociatedObject(self, &kInstalledConstraintsKey);
    if (!constraints) {
        constraints = [NSMutableSet set];
        objc_setAssociatedObject(self, &kInstalledConstraintsKey, constraints, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return constraints;
}

@end

同MASCompositeConstraint類一樣,在.m文件里面MASViewConstraint也重寫了很多的父類的方法,結(jié)構(gòu)很清晰。

下面看一下該類的結(jié)構(gòu)

MASViewConstraint

在.h中只暴露出來(lái)一個(gè)實(shí)例化方法和返回所有已安裝約束的方法。在.m中重寫了很多父類的方法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容