您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

自定義 UICollectionView 的頭/尾視圖:UICollectionReusableView 實戰

編輯:iOS 開發綜合

顧名思義,要自定義 UICollectionView 的補充視圖,就是繼承 UICollectionReusableView,做出一個符合需求的視圖。整個流程可以拆成註冊、提供、填充三步。

一、控制器中註冊並提供補充視圖

#import "ViewController.h"
#import "LSHControl.h"
#import "SHCollectionReusableView.h"
#import "SHCollectionViewCell.h"

#define SHCollectionViewCellIdetifiler @"CollectionViewCell"
#define SHCollectionReusableViewHeader @"CollectionHeader"
#define SHCollectionReusableViewFooter @"CollectionFooter"

@interface ViewController () <UICollectionViewDelegate, UICollectionViewDataSource> {
    NSArray *recipeImages;
    NSArray *hearderTitleArray;
}
@property (nonatomic, strong) UICollectionView *rightCollectionView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *mainDishImages = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"full_breakfast.jpg", @"ham_and_cheese_panini.jpg", @"ham_and_egg_sandwich.jpg", @"hamburger.jpg", @"instant_noodle_with_egg.jpg", @"japanese_noodle_with_pork.jpg", @"mushroom_risotto.jpg", @"noodle_with_bbq_pork.jpg", @"thai_shrimp_cake.jpg", @"vegetable_curry.jpg", nil];
    NSArray *drinkDessertImages = [NSArray arrayWithObjects:@"angry_birds_cake.jpg", @"creme_brelee.jpg", @"green_tea.jpg", @"starbucks_coffee.jpg", @"white_chocolate_donut.jpg", nil];
    recipeImages = [NSArray arrayWithObjects:mainDishImages, drinkDessertImages, nil];
    hearderTitleArray = @[@"分區1", @"分區2"];
    [self createCollectionView];
}

-(void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0.f;
    flowLayout.minimumLineSpacing = 5.f;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 15, 5, 15);
    flowLayout.itemSize = CGSizeMake(80, 80);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 30);
    flowLayout.footerReferenceSize = CGSizeMake(self.view.frame.size.width, 30);

    self.rightCollectionView = [LSHControl createCollectionViewFromFrame:self.view.frame collectionViewLayout:flowLayout dataSource:self delegate:self backgroudColor:[UIColor whiteColor]];

    [self.rightCollectionView registerNib:[UINib nibWithNibName:@"SHCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:SHCollectionViewCellIdetifiler];
    [self.rightCollectionView registerClass:[SHCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:SHCollectionReusableViewHeader];
    [self.rightCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:SHCollectionReusableViewFooter];

    [self.view addSubview:self.rightCollectionView];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [recipeImages count];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [[recipeImages objectAtIndex:section] count];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        SHCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:SHCollectionReusableViewHeader forIndexPath:indexPath];
        // 雖然這裡沒看到 initWithFrame,但系統在取用重用視圖時會自動呼叫它,
        // 因此把初始化邏輯寫在 initWithFrame 中是安全的。
        [headerView getSHCollectionReusableViewHearderTitle:hearderTitleArray[indexPath.section]];
        reusableview = headerView;
    }
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:SHCollectionReusableViewFooter forIndexPath:indexPath];
        // 內容簡單時直接設定屬性即可,不必自定義
        footerview.backgroundColor = [UIColor redColor];
        reusableview = footerview;
    }
    return reusableview;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SHCollectionViewCell *cell = (SHCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:SHCollectionViewCellIdetifiler forIndexPath:indexPath];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame-2.png"]];
    return cell;
}
@end

二、用 xib 佈局的自定義 Cell

#import <UIKit/UIKit.h>

@interface SHCollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *recipeImageView;
@end

@implementation SHCollectionViewCell
@end

三、手寫程式碼佈局的自定義 ReusableView

頭文件只需要對外暴露一個賦值方法,或者直接宣告資料模型屬性:

#import <UIKit/UIKit.h>

@interface SHCollectionReusableView : UICollectionReusableView
-(void)getSHCollectionReusableViewHearderTitle:(NSString *)title;
@end

實作檔在 initWithFrame: 中完成子視圖建立,這也是推薦的做法,因為重用機制一定會經過這個初始化入口:

#import "SHCollectionReusableView.h"
#import "LSHControl.h"

@interface SHCollectionReusableView () {
    UILabel *titleLabel;
}
@end

@implementation SHCollectionReusableView

-(id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor greenColor];
        [self createBasicView];
    }
    return self;
}

-(void)createBasicView {
    titleLabel = [LSHControl createLabelWithFrame:CGRectMake(5, 0, self.frame.size.width - 50, self.frame.size.height)
                                            Font:[UIFont systemFontOfSize:14.0]
                                            Text:@""
                                           color:[UIColor grayColor]];
    [self addSubview:titleLabel];
}

-(void)getSHCollectionReusableViewHearderTitle:(NSString *)title {
    titleLabel.text = title;
}
@end

效果如下:

小結一下三個要點:註冊時區分 UICollectionElementKindSectionHeader 與 Footer;初始化邏輯放 initWithFrame:;資料透過公開方法或屬性注入,不要在 viewForSupplementaryElementOfKind: 裡重建子視圖。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved