欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

UICollectionView使用

程序员文章站 2022-09-06 11:22:35
一、视图控制器基础代码UICollectionView需要用UICollectionViewFlowLayout初始化。注册cell、header、footer以提供复用。// UserViewController.h#import @interface UserViewController : UIViewController@property (nonatomic, strong) UICollectionView *collectionView;...

一、视图控制器基础代码

UICollectionView需要用UICollectionViewFlowLayout初始化。注册cell、header、footer以提供复用。

//  UserViewController.h

#import <UIKit/UIKit.h>
@interface UserViewController : UIViewController
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@end
//  UserViewController.m

#import "UserViewController.h"
#import "HeaderCollectionReusableView.h"
#import "FooterCollectionReusableView.h"
#import "UserImageModel.h"
#import "CollectionViewCell.h"
#define ScreenWidth self.view.bounds.size.width
#define ScreenHeight self.view.bounds.size.height

//注册用
static NSString *const cellIdentifier = @"cellIdentifier";
static NSString *const headerIdentifier = @"headerIdentifier";
static NSString *const footerIdentifier = @"footerIdentifier";

@interface UserViewController ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate>
@end

@implementation UserViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self.collectionView reloadData];//刷新数据
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createView];
}

- (void)createView
{
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:_flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.view addSubview:_collectionView];
    //collectionView的初始化
    
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    [self.collectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
    [self.collectionView registerClass:[FooterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier];
}

二、数据源

//  UserImageModel.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UserImageModel : NSObject
+ (instancetype)sharedImage;
- (NSArray *)allItems;
- (void)addItemWithImage:(UIImage *)image;
@end


//  UserImageModel.m

#import "UserImageModel.h"
@interface UserImageModel()
@property (nonatomic)NSMutableArray *privateItems;
@end

@implementation UserImageModel
+ (instancetype)sharedImage
{
    static UserImageModel *sharedImage = nil;
    if(!sharedImage){
        sharedImage = [[self alloc] initPrivate];
    }
    return sharedImage;
}

- (instancetype)init
{
    @throw [NSException exceptionWithName:@"Singleton"
                                   reason:@"use +[UserImageModel sharedImage]"
                                 userInfo:nil];
    return nil;
}

- (instancetype)initPrivate
{
    self = [super init];
    if(self){
        _privateItems = [[NSMutableArray alloc] init];
    }
    return self;
}

- (NSArray *)allItems
{
    return self.privateItems;
}

- (void)addItemWithImage:(UIImage *)image
{
    [self.privateItems addObject:image];
}
@end

三、实现协议UICollectionViewDataSource


#pragma mark - UICollectionViewDataSource

//collectionView中section数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

//每个section的item数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(section == 0){
        return 0;
    }
    return [[UserImageModel sharedImage] allItems].count;
}

//具体每个item的cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.imageView.image = [[[UserImageModel sharedImage] allItems] objectAtIndex:indexPath.item];
    cell.label.text = [NSString stringWithFormat:@"( %d )",indexPath.item];
    return cell;
}

//collectionView中的header与footer
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            HeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
            return headerView;
        } else if([kind isEqualToString:UICollectionElementKindSectionFooter]){
            FooterCollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier forIndexPath:indexPath];
            return footerView;
        }
    }
    return nil;
}

四、实现协议UICollectionViewDelegateFlowLayout调整布局

#pragma mark - UICollectionViewDelegateFlowLayout

//设置item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(ScreenWidth *0.3, 128);
}

//设置section的header和footer大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if(section == 0){
        return CGSizeMake(ScreenWidth, ScreenHeight * 0.35);
    }else{
        return CGSizeMake(0, 0);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if(section == 0){
        return CGSizeMake(ScreenWidth, ScreenHeight * 0.05);
    }else{
        return CGSizeMake(0, 0);
    }
}

//设置内边距 上左下右
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 1, 0, 1);
}

//设置行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

//设置item间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

五、实现协议UICollectionViewDelegate以达成某些功能

#pragma mark - UICollectionViewDelegate
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView cellForItemAtIndexPath:indexPath].backgroundColor = [UIColor blackColor];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

@end

六、自定义UICollectionViewCell

//  CollectionViewCell.h

#import <UIKit/UIKit.h>

@interface CollectionViewCell : UICollectionViewCell
@property (nonatomic, strong)UIImageView *imageView;
@property (nonatomic, strong)UILabel *label;
@end


//  CollectionViewCell.m

#import "CollectionViewCell.h"

@implementation CollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        CGFloat cellWidth = self.bounds.size.width;
        CGFloat cellHeight = self.bounds.size.height;
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cellWidth, cellHeight * 4/5)];
        _label = [[UILabel alloc] initWithFrame:CGRectMake(0, cellHeight * 4/5, cellWidth, cellHeight * 1/5)];
        _label.textAlignment = NSTextAlignmentCenter;
        _label.backgroundColor = [UIColor blackColor];
        [self.contentView addSubview:_imageView];
        [self.contentView addSubview:_label];
    }
    return self;
}
@end

七、自定义Header(Footer)

Header(Footer)是UICollectionReusableView的子类

//  HeaderCollectionReusableView.h

#import <UIKit/UIKit.h>
@interface HeaderCollectionReusableView : UICollectionReusableView
@end

//  HeaderCollectionReusableView.m

#import "HeaderCollectionReusableView.h"

@interface HeaderCollectionReusableView()
@property (nonatomic, strong)UIButton *topImage;
@property (nonatomic, strong)UIButton *headImage;
@property (nonatomic, strong)UIButton *setButton;
@property (nonatomic, strong)UIButton *editButton;
@property (nonatomic, strong)UILabel *userName;
@end

@implementation HeaderCollectionReusableView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColor blackColor];
        [self setUI];
    }
    return self;
}

- (void)setUI
{
    CGFloat HeaderWidth = self.bounds.size.width;
    CGFloat HeaderHeight = self.bounds.size.height;
    self.topImage = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, HeaderWidth, HeaderHeight * 1/3)];
    _topImage.contentMode = UIViewContentModeScaleAspectFit;
    _topImage.backgroundColor = [UIColor redColor];
    [self addSubview:_topImage];
    
    self.headImage = [[UIButton alloc] initWithFrame:CGRectMake(20, HeaderHeight * 1/3, 80, 80)];
    _headImage.layer.cornerRadius = _headImage.frame.size.width/2;
    _headImage.layer.masksToBounds = YES;
    _headImage.contentMode = UIViewContentModeScaleAspectFit;
    _headImage.backgroundColor = [UIColor blueColor];
    [self addSubview:_headImage];
    
    self.editButton = [[UIButton alloc] initWithFrame:CGRectMake(100, HeaderHeight * 1/3, 200, 50)];
    _editButton.backgroundColor = [UIColor darkGrayColor];
    [_editButton setTitle:@"编辑资料" forState:UIControlStateNormal];
    [_editButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_editButton.titleLabel setTextColor:[UIColor whiteColor]];
    [self addSubview:_editButton];
    
    self.setButton = [[UIButton alloc] initWithFrame:CGRectMake(HeaderWidth - 60, 50, 40, 40)];
    _setButton.backgroundColor = [UIColor darkGrayColor];
    [_setButton setTitle:@"设置" forState:UIControlStateNormal];
    [_setButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_setButton.titleLabel setTextColor:[UIColor whiteColor]];
    [self addSubview:_setButton];
    
    self.userName = [[UILabel alloc] initWithFrame:CGRectMake(10, HeaderHeight * 2/3, 100, 50)];
    _userName.backgroundColor = [UIColor clearColor];
    _userName.text = @"测试名字";
    [_userName setTextColor:[UIColor whiteColor]];
    [self addSubview:_userName];
}
@end


本文地址:https://blog.csdn.net/weixin_44611644/article/details/107286390