UICollectionview 設置 section background

1.需求:

在同一個頁面展示分類items槽驶,類別之間使用特定的“容器”視圖包裹此分類下的所有元素老虫,分類頭部和尾部要顯示相關數(shù)據(jù)。如下圖:

image
2.可選方案:
  1. 使用UITableView或者UICollectionView黍衙,一個分類就是一個cell或者item冕象, 每個cell或item內(nèi)再繪制類別下所有元素。
  2. 使用UICollectionView龟梦,每個元素都是一個item隐锭,這時候就需要想辦法,把相應的item給“包”起來计贰。

方案“1”無疑是最簡單的實現(xiàn)钦睡,但是如果當一個類別的元素特別多,而且類別需要顯示的UI特別復雜(例如一個cell里面有N多個元素)躁倒,就會因為這個大cell需要一次性繪制荞怒,包括沒有顯示在屏幕內(nèi)的元素,會造成性能問題秧秉。
所以我們來探討一下方案“2”的實現(xiàn)褐桌。

3. 實現(xiàn):

每個類別header、section象迎、footer上中下三層荧嵌,底下一個DecorationView。

image
image

創(chuàng)建一個UICollectionView砾淌,使用自定義的layout(繼承UICollectionViewFlowLayout)啦撮。

#import "ViewController.h"
#import "HVWLayout.h"
#import "HVWHeader.h"
#import "HVWFooter.h"

@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;

    HVWLayout *layout = [[HVWLayout alloc] init];
    layout.itemSize = CGSizeMake(80, 80);
    layout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, 90);
    layout.footerReferenceSize = CGSizeMake(self.view.bounds.size.width, 70);
    layout.sectionInset = UIEdgeInsetsMake(0, 30, 0, 30);
    layout.minimumLineSpacing = 20;
    layout.minimumInteritemSpacing = ([UIScreen mainScreen].bounds.size.width - 80 * 3 - 60) / 2;

    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:collectionView];

    collectionView.dataSource = self;
    collectionView.delegate = self;

    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [collectionView registerClass:[HVWHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [collectionView registerClass:[HVWFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 10;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return section + 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor orangeColor];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        return [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];

    } else if (kind == UICollectionElementKindSectionFooter) {
        return [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
    }

    return nil;
}

#pragma mark - UICollectionViewDelegate

@end

在layout里面配置DecorationView,計算出位置汪厨。

#import "HVWLayout.h"
#import "HVWDecorationView.h"

@implementation HVWLayout

- (void)prepareLayout {
    [super prepareLayout];

    [self registerClass:[HVWDecorationView class] forDecorationViewOfKind:@"decorationView"];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath top:(CGFloat)top {
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:elementKind withIndexPath:indexPath];

    NSUInteger numberOfItems = [self.collectionView numberOfItemsInSection:indexPath.section];
    int itemsPerRow = 3;
    NSUInteger rows = (numberOfItems + itemsPerRow - 1) / itemsPerRow;
    CGFloat cellHeight = 80;
    CGFloat cellSpace = 20;
    CGFloat headerHeigh = 90;
    CGFloat footerHeight = 70;
    CGFloat height = headerHeigh + cellHeight * rows + cellSpace * (rows - 1) + footerHeight;

    attrs.frame = CGRectMake(0, top, [UIScreen mainScreen].bounds.size.width, height);
    attrs.zIndex = -1;
//    NSLog(@"%s", __func__);

    return attrs;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *superAttrs = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray *attrs = [NSMutableArray arrayWithArray:superAttrs];

    for (UICollectionViewLayoutAttributes *attr in superAttrs) {
        if (attr.representedElementKind == UICollectionElementKindSectionHeader) {
            [attrs addObject:[self layoutAttributesForDecorationViewOfKind:@"decorationView" atIndexPath:attr.indexPath top:attr.frame.origin.y]];
        }
    }

//    NSLog(@"%s", __func__);

    return attrs;
}

在DecorationView中赃春,重寫方法applyLayoutAttributes,重新計算布局view內(nèi)的元素劫乱。

注意不能靠重寫setFrame或者layoutSubViews來布局织中,因為這兩方法只在初始化的時候調(diào)用一次,重用就不會調(diào)用了衷戈。

#import "HVWDecorationView.h"

@interface HVWDecorationView()

@property(nonatomic, strong) UIImageView *imageView;

@end

@implementation HVWDecorationView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
//        self.backgroundColor = [UIColor grayColor];

        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, frame.size.width - 20, frame.size.height - 20)];
        UIImage *image = [UIImage imageNamed:@"bg"];
        _imageView.image = [image stretchableImageWithLeftCapWidth:image.size.width/2 topCapHeight:image.size.height/2];
        [self addSubview:_imageView];
    }

    return self;
}

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    [super applyLayoutAttributes:layoutAttributes];
//    NSLog(@"%s", __func__);

    _imageView.frame = CGRectMake(10, 10, layoutAttributes.frame.size.width - 20, layoutAttributes.frame.size.height - 20);
}

作者:西蒙SIMON
鏈接:http://www.reibang.com/p/565dfb3c23d1
來源:簡書
簡書著作權歸作者所有抠璃,任何形式的轉(zhuǎn)載都請聯(lián)系作者獲得授權并注明出處。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末脱惰,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子窿春,更是在濱河造成了極大的恐慌拉一,老刑警劉巖采盒,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異蔚润,居然都是意外死亡磅氨,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門嫡纠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來烦租,“玉大人,你說我怎么就攤上這事除盏〔娉鳎” “怎么了?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵者蠕,是天一觀的道長窃祝。 經(jīng)常有香客問我,道長踱侣,這世上最難降的妖魔是什么粪小? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮抡句,結(jié)果婚禮上粤攒,老公的妹妹穿的比我還像新娘。我一直安慰自己篮撑,他們只是感情好沃琅,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著究抓,像睡著了一般猾担。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上刺下,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天绑嘹,我揣著相機與錄音,去河邊找鬼橘茉。 笑死工腋,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的畅卓。 我是一名探鬼主播擅腰,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼翁潘!你這毒婦竟也來了趁冈?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎渗勘,沒想到半個月后沐绒,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡旺坠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年乔遮,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片取刃。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡蹋肮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出璧疗,到底是詐尸還是另有隱情坯辩,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布病毡,位于F島的核電站濒翻,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏啦膜。R本人自食惡果不足惜有送,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望僧家。 院中可真熱鬧雀摘,春花似錦、人聲如沸八拱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽肌稻。三九已至清蚀,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間爹谭,已是汗流浹背枷邪。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留诺凡,地道東北人东揣。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像腹泌,于是被迫代替她去往敵國和親嘶卧。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355

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

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,103評論 1 32
  • iOS流布局UICollectionView系列一——初識與簡單使用UICollectionView 一凉袱、簡介 U...
    我是啊梁閱讀 10,481評論 3 10
  • 原文地址:http://www.reibang.com/p/db55bd5f5aeb[https://www.j...
    移動端_小剛哥閱讀 2,903評論 7 18
  • UICollectionView是開發(fā)中用的比較多的一個控件芥吟,本文記錄UICollectionView在開發(fā)中常用...
    aron1992閱讀 21,645評論 5 39
  • 最近將 UICollectionView 進行了一個全面的學習及總結(jié),參考了網(wǎng)上大量的文章,把官方文檔進行了大概翻...
    varlarzh閱讀 21,442評論 3 94