iOS Masonry實(shí)現(xiàn)九宮格布局

直接復(fù)制下面代碼看效果
一济竹、常規(guī)布局方式


517349-20160819194720781-2023804629.png
517349-20160819194712937-1138283651.png
517349-20160819194657703-1828190789.png
- (void)viewDidLoad {
    [super viewDidLoad];
    // TODO: 創(chuàng)建一個裝載九宮格的容器
    UIView *containerView = [[UIView alloc] init];
    [self.view addSubview:containerView];
    containerView.backgroundColor = [UIColor whiteColor];
    containerView.layer.borderWidth = 1;
    containerView.layer.borderColor = [UIColor grayColor].CGColor;
    
   // TODO:給該容器添加布局代碼
    [containerView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(15);
        make.top.equalTo(66);
        make.right.equalTo(-15);
        make.height.equalTo(300);
    }];

    // TODO:  為該容器添加宮格View 
    for (int i = 0; i < 10; i++) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor randomColor];
        [containerView addSubview:view];
    }

    // TODO: 執(zhí)行九宮格布局

   /*
     一行代碼梦谜,就可以實(shí)現(xiàn)九宮格布局
     
     -[NSArray mas_distributeSudokuViewsWithFixedItemWidth:fixedItemHeight:fixedLineSpacing:fixedInteritemSpacing:warpCount:topSpacing:bottomSpacing:leadSpacing:tailSpacing:]
     
     參數(shù)介紹:
     
     fixedItemWidth: 宮格的寬度袭景,如果設(shè)置為0的話耸棒,則由父容器控制寬度报辱,如果不為零,則可以控制父容器的寬度
     
     fixedItemHeight:與fixedItemWidth同理
     
     fixedLineSpacing:宮格之間行的間距幅疼,如果宮格只有一行昼接,則不生效
     
     fixedInteritemSpacing:宮格之間列的間距慢睡,如果只有一列漂辐,則不生效
     
     warpCount:折行的位置,如果設(shè)置為3瘤泪,則表示該九宮格需要布局3列膳犹,值得一提的是,如果NSArray本身的count如果小于warpCount豺旬,則該函數(shù)會用空的UIView填充到缺失區(qū)域篓跛。
     
     topSpacing:bottomSpacing:leadSpacing:tailSpacing:九宮格頂邊距愧沟,底邊距,左邊距以及右邊距
     */

  [containerView.subviews  mas_distributeSudokuViewsWithFixedItemWidth:0
                                                        fixedItemHeight:0
                                                       fixedLineSpacing:10
                                                  fixedInteritemSpacing:20
                                                              warpCount:3
                                                             topSpacing:10
                                                          bottomSpacing:10
                                                            leadSpacing:10
                                                            tailSpacing:10];
    
}

二、另外一種布局方式

517349-20160819200905937-430060348.png

view創(chuàng)建代碼不變 masnory實(shí)現(xiàn)代碼如下

/**
 *  九宮格布局 固定ItemSize 可變ItemSpacing
 *
 *  @param fixedItemWidth  固定寬度
 *  @param fixedItemHeight 固定高度
 *  @param warpCount       折行點(diǎn)
 *  @param topSpacing      頂間距
 *  @param bottomSpacing   底間距
 *  @param leadSpacing     左間距
 *  @param tailSpacing     右間距
 */
/*
- (void)mas_distributeSudokuViewsWithFixedItemWidth:(CGFloat)fixedItemWidth
                                    fixedItemHeight:(CGFloat)fixedItemHeight
                                          warpCount:(NSInteger)warpCount
                                         topSpacing:(CGFloat)topSpacing
                                      bottomSpacing:(CGFloat)bottomSpacing
                                        leadSpacing:(CGFloat)leadSpacing
                                        tailSpacing:(CGFloat)tailSpacing;
 */
[containerView.subviews mas_distributeSudokuViewsWithFixedItemWidth:50
                                                       fixedItemHeight:50
                                                             warpCount:3
                                                            topSpacing:10
                                                         bottomSpacing:10
                                                           leadSpacing:10
                                                           tailSpacing:10];

// !!!: 實(shí)現(xiàn)如下 給數(shù)組加一個擴(kuò)展

.h

#import "MASUtilities.h"
#import "MASConstraintMaker.h"
#import "MASViewAttribute.h"

@interface NSArray (Sudoku)


/**
 *  九宮格布局 固定ItemSize 可變ItemSpacing
 *
 *  @param fixedItemWidth  固定寬度
 *  @param fixedItemHeight 固定高度
 *  @param warpCount       折行點(diǎn)
 *  @param topSpacing      頂間距
 *  @param bottomSpacing   底間距
 *  @param leadSpacing     左間距
 *  @param tailSpacing     右間距
 */
- (void)mas_distributeSudokuViewsWithFixedItemWidth:(CGFloat)fixedItemWidth
                                    fixedItemHeight:(CGFloat)fixedItemHeight
                                          warpCount:(NSInteger)warpCount
                                         topSpacing:(CGFloat)topSpacing
                                      bottomSpacing:(CGFloat)bottomSpacing
                                        leadSpacing:(CGFloat)leadSpacing
                                        tailSpacing:(CGFloat)tailSpacing;


/**
 *  九宮格布局 可變ItemSize 固定ItemSpacing
 *
 *  @param fixedLineSpacing      行間距
 *  @param fixedInteritemSpacing 列間距
 *  @param warpCount             折行點(diǎn)
 *  @param topSpacing            頂間距
 *  @param bottomSpacing         底間距
 *  @param leadSpacing           左間距
 *  @param tailSpacing           右間距
 */
- (void)mas_distributeSudokuViewsWithFixedLineSpacing:(CGFloat)fixedLineSpacing
                                fixedInteritemSpacing:(CGFloat)fixedInteritemSpacing
                                            warpCount:(NSInteger)warpCount
                                           topSpacing:(CGFloat)topSpacing
                                        bottomSpacing:(CGFloat)bottomSpacing
                                          leadSpacing:(CGFloat)leadSpacing
                                          tailSpacing:(CGFloat)tailSpacing;


/**
 *  九宮格布局 固定ItemSize 固定ItemSpacing
 *  可由九宮格的內(nèi)容控制SuperView的大小
 *  如果warpCount大于[self count],該方法將會用空白的View填充到superview中
 *
 *  Sudoku Layout, has fixed item size, and fix item space
 *  If warp count greater than self.count, It's fill empty view to superview
 *
 *  @param fixedItemWidth        固定寬度,如果設(shè)置成0,則表示自適應(yīng)闲坎,If set it to zero, indicates the adaptive.
 *  @param fixedItemHeight       固定高度,如果設(shè)置成0慷彤,則表示自適應(yīng)瞬欧,If set it to zero, indicates the adaptive.
 *  @param fixedLineSpacing      行間距
 *  @param fixedInteritemSpacing 列間距
 *  @param warpCount             折行點(diǎn)
 *  @param topSpacing            頂間距
 *  @param bottomSpacing         底間距
 *  @param leadSpacing           左間距
 *  @param tailSpacing           右間距
 *
 *  @return 一般情況下會返回[self copy], 如果warpCount大于[self count]咒吐,則會返回一個被空白view填充過的數(shù)組恬叹,可以讓你循環(huán)調(diào)用removeFromSuperview或者干一些其他的事情;
 *  @return Normal will return [self copy], If warpCount bigger than [self count] , It will return a empty views filled array, you could enumerate [subview removeFromSuperview] or do other things;
 */
- (NSArray *)mas_distributeSudokuViewsWithFixedItemWidth:(CGFloat)fixedItemWidth
                                         fixedItemHeight:(CGFloat)fixedItemHeight
                                        fixedLineSpacing:(CGFloat)fixedLineSpacing
                                   fixedInteritemSpacing:(CGFloat)fixedInteritemSpacing
                                               warpCount:(NSInteger)warpCount
                                              topSpacing:(CGFloat)topSpacing
                                           bottomSpacing:(CGFloat)bottomSpacing
                                             leadSpacing:(CGFloat)leadSpacing
                                             tailSpacing:(CGFloat)tailSpacing;
@end

.m

#import "NSArray+Sudoku.h"
#import "View+MASAdditions.h"

@implementation NSArray (Sudoku)


- (MAS_VIEW *)star_commonSuperviewOfViews {
    
    if (self.count == 1) {
        return ((MAS_VIEW *)self.firstObject).superview;
    }
    
    MAS_VIEW *commonSuperview = nil;
    MAS_VIEW *previousView = nil;
    for (id object in self) {
        if ([object isKindOfClass:[MAS_VIEW class]]) {
            MAS_VIEW *view = (MAS_VIEW *)object;
            if (previousView) {
                commonSuperview = [view mas_closestCommonSuperview:commonSuperview];
            } else {
                commonSuperview = view;
            }
            previousView = view;
        }
    }
    NSAssert(commonSuperview, @"Can't constrain views that do not share a common superview. Make sure that all the views in this array have been added into the same view hierarchy.");
    return commonSuperview;
}



- (void)mas_distributeSudokuViewsWithFixedItemWidth:(CGFloat)fixedItemWidth
                                    fixedItemHeight:(CGFloat)fixedItemHeight
                                          warpCount:(NSInteger)warpCount
                                         topSpacing:(CGFloat)topSpacing
                                      bottomSpacing:(CGFloat)bottomSpacing
                                        leadSpacing:(CGFloat)leadSpacing
                                        tailSpacing:(CGFloat)tailSpacing {
    if (self.count < 2) {
        NSAssert(self.count>1,@"views to distribute need to bigger than one");
        return;
    }
    if (warpCount < 1) {
        NSAssert(false, @"warp count need to bigger than zero");
        return;
    }
    
    MAS_VIEW *tempSuperView = [self star_commonSuperviewOfViews];
    
    NSInteger rowCount = self.count % warpCount == 0 ? self.count / warpCount : self.count / warpCount + 1;
    
    MAS_VIEW *prev;
    for (int i = 0; i < self.count; i++) {
        
        MAS_VIEW *v = self[i];
        
        // 當(dāng)前行
        NSInteger currentRow = i / warpCount;
        // 當(dāng)前列
        NSInteger currentColumn = i % warpCount;
        
        [v mas_makeConstraints:^(MASConstraintMaker *make) {
            // 固定寬度
            make.width.equalTo(@(fixedItemWidth));
            make.height.equalTo(@(fixedItemHeight));
            
            // 第一行
            if (currentRow == 0) {
                make.top.equalTo(tempSuperView).offset(topSpacing);
            }
            // 最后一行
            if (currentRow == rowCount - 1) {
                make.bottom.equalTo(tempSuperView).offset(-bottomSpacing);
            }
            // 中間的若干行
            if (currentRow != 0 && currentRow != rowCount - 1){
                CGFloat offset = (1-(currentRow/((CGFloat)rowCount-1)))*(fixedItemHeight+topSpacing)-currentRow*bottomSpacing/(((CGFloat)rowCount-1));
                make.bottom.equalTo(tempSuperView).multipliedBy(currentRow/((CGFloat)rowCount-1)).offset(offset);
            }
            
            // 第一列
            if (currentColumn == 0) {
                make.left.equalTo(tempSuperView).offset(leadSpacing);
            }
            // 最后一列
            if (currentColumn == warpCount - 1) {
                make.right.equalTo(tempSuperView).offset(-tailSpacing);
            }
            // 中間若干列
            if (currentColumn != 0 && currentColumn != warpCount - 1) {
                CGFloat offset = (1-(currentColumn/((CGFloat)warpCount-1)))*(fixedItemWidth+leadSpacing)-currentColumn*tailSpacing/(((CGFloat)warpCount-1));
                make.right.equalTo(tempSuperView).multipliedBy(currentColumn/((CGFloat)warpCount-1)).offset(offset);
            }
        }];
        prev = v;
    }
}

- (void)mas_distributeSudokuViewsWithFixedLineSpacing:(CGFloat)fixedLineSpacing
                                fixedInteritemSpacing:(CGFloat)fixedInteritemSpacing
                                            warpCount:(NSInteger)warpCount
                                           topSpacing:(CGFloat)topSpacing
                                        bottomSpacing:(CGFloat)bottomSpacing
                                          leadSpacing:(CGFloat)leadSpacing
                                          tailSpacing:(CGFloat)tailSpacing {
    
    [self mas_distributeSudokuViewsWithFixedItemWidth:0 fixedItemHeight:0 fixedLineSpacing:fixedLineSpacing fixedInteritemSpacing:fixedInteritemSpacing warpCount:warpCount topSpacing:topSpacing bottomSpacing:bottomSpacing leadSpacing:leadSpacing tailSpacing:tailSpacing];
}

- (NSArray *)mas_distributeSudokuViewsWithFixedItemWidth:(CGFloat)fixedItemWidth
                                         fixedItemHeight:(CGFloat)fixedItemHeight
                                        fixedLineSpacing:(CGFloat)fixedLineSpacing
                                   fixedInteritemSpacing:(CGFloat)fixedInteritemSpacing
                                               warpCount:(NSInteger)warpCount
                                              topSpacing:(CGFloat)topSpacing
                                           bottomSpacing:(CGFloat)bottomSpacing
                                             leadSpacing:(CGFloat)leadSpacing
                                             tailSpacing:(CGFloat)tailSpacing {
    if (self.count < 1) {
        return self.copy;
    }
    if (warpCount < 1) {
        NSAssert(false, @"warp count need to bigger than zero");
        return self.copy;
    }
    
    MAS_VIEW *tempSuperView = [self star_commonSuperviewOfViews];
    
    NSArray *tempViews = self.copy;
    if (warpCount > self.count) {
        for (int i = 0; i < warpCount - self.count; i++) {
            MAS_VIEW *tempView = [[MAS_VIEW alloc] init];
            [tempSuperView addSubview:tempView];
            tempViews = [tempViews arrayByAddingObject:tempView];
        }
    }
    
    NSInteger columnCount = warpCount;
    NSInteger rowCount = tempViews.count % columnCount == 0 ? tempViews.count / columnCount : tempViews.count / columnCount + 1;
    
    MAS_VIEW *prev;
    for (int i = 0; i < tempViews.count; i++) {
        
        MAS_VIEW *v = tempViews[i];
        NSInteger currentRow = i / columnCount;
        NSInteger currentColumn = i % columnCount;
        
        [v mas_makeConstraints:^(MASConstraintMaker *make) {
            if (prev) {
                // 固定寬度
                make.width.equalTo(prev);
                make.height.equalTo(prev);
            }
            else {
                // 如果寫的item高寬分別是0循未,則表示自適應(yīng)
                if (fixedItemWidth) {
                    make.width.equalTo(@(fixedItemWidth));
                }
                if (fixedItemHeight) {
                    make.height.equalTo(@(fixedItemHeight));
                }
            }
            
            // 第一行
            if (currentRow == 0) {
                make.top.equalTo(tempSuperView).offset(topSpacing);
            }
            // 最后一行
            if (currentRow == rowCount - 1) {
                // 如果只有一行
                if (currentRow != 0 && i-columnCount >= 0) {
                    make.top.equalTo(((MAS_VIEW *)tempViews[i-columnCount]).mas_bottom).offset(fixedLineSpacing);
                }
                make.bottom.equalTo(tempSuperView).offset(-bottomSpacing);
            }
            // 中間的若干行
            if (currentRow != 0 && currentRow != rowCount - 1) {
                make.top.equalTo(((MAS_VIEW *)tempViews[i-columnCount]).mas_bottom).offset(fixedLineSpacing);
            }
            
            // 第一列
            if (currentColumn == 0) {
                make.left.equalTo(tempSuperView).offset(leadSpacing);
            }
            // 最后一列
            if (currentColumn == columnCount - 1) {
                // 如果只有一列
                if (currentColumn != 0) {
                    make.left.equalTo(prev.mas_right).offset(fixedInteritemSpacing);
                }
                make.right.equalTo(tempSuperView).offset(-tailSpacing);
            }
            // 中間若干列
            if (currentColumn != 0 && currentColumn != warpCount - 1) {
                make.left.equalTo(prev.mas_right).offset(fixedInteritemSpacing);
            }
        }];
        prev = v;
    }
    return tempViews;
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末娇未,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子搁凸,更是在濱河造成了極大的恐慌褥芒,老刑警劉巖锰扶,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異颜及,居然都是意外死亡俏站,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進(jìn)店門犯祠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人月劈,你說我怎么就攤上這事《悖” “怎么了?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長公般。 經(jīng)常有香客問我官帘,道長刽虹,這世上最難降的妖魔是什么意敛? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任稍刀,我火速辦了婚禮账月,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘橄登。我一直安慰自己谣妻,他們只是感情好蹋半,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布捻爷。 她就那樣靜靜地躺著役衡,像睡著了一般榕莺。 火紅的嫁衣襯著肌膚如雪钉鸯。 梳的紋絲不亂的頭發(fā)上贸营,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死扇调,一個胖子當(dāng)著我的面吹牛狼钮,可吹牛的內(nèi)容都是我干的燃领。 我是一名探鬼主播猛蔽,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼略板,長吁一口氣:“原來是場噩夢啊……” “哼种玛!你這毒婦竟也來了赂韵?” 一聲冷哼從身側(cè)響起肄满,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎怒炸,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡耕肩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了址芯。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谷炸。...
    茶點(diǎn)故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖语婴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情场航,我是刑警寧澤旗闽,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布举瑰,位于F島的核電站汽畴,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜嘁酿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一沐飘、第九天 我趴在偏房一處隱蔽的房頂上張望众弓。 院中可真熱鬧谓娃,春花似錦奶稠、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至跑芳,卻和暖如春博个,著一層夾襖步出監(jiān)牢的瞬間坡倔,已是汗流浹背投蝉。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人归露。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓疆液,卻偏偏與公主長得像堕油,于是被迫代替她去往敵國和親卜录。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評論 2 355

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

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,133評論 25 707
  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 13,753評論 1 92
  • 翻譯自“Collection View Programming Guide for iOS” 0 關(guān)于iOS集合視...
    lakerszhy閱讀 3,864評論 1 22
  • 二級標(biāo)題 引語涵卵。與上面必須空一行典鸡,要不然這個一點(diǎn)都不好用的客戶端的編輯器死活不好控制引語范圍。 代碼呢球碉?怎么插? ...
    Youth霖閱讀 209評論 0 0
  • 當(dāng)不愛的時候拓巧,請不要失去自己的自信傻唾。因?yàn)閻垡粋€人,并非因他的優(yōu)秀凛辣,而只是一種感覺。他讓你有這樣的感覺,于是你愛他前普。...
    文靜視界閱讀 266評論 0 1