UICollectionview的使用详解

简介: 三个代理<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>前两个的用法和tableView的很像,第三个是布局的协议。(注意:头视图尾视图都是由代理方法获得,而且需要写注册,缺少了也不行。) 注册以后,就不需要再去管理复用的问题了。这点就很简单。这个如果用好的话,会非常的简单。
  1. 三个代理


<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
前两个的用法和tableView的很像,第三个是布局的协议。(注意:头视图尾视图都是由代理方法获得,而且需要写注册,缺少了也不行。) 注册以后,就不需要再去管理复用的问题了。这点就很简单。这个如果用好的话,会非常的简单。


  1. item(即cell)的布局原理(类似tableView)


  1. header/footer View的布局原理


都是继承于UICollectionReusableView,并且必须要从dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:这个代理方法中获取,而且根据不同的kind作为headerView或者footerView,切记:collectionView中头部视图和尾部视图也需要注册

下面直接上代码,看注释即可:


ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
}
@property (strong, nonatomic)UICollectionView *collectionView;
@end


ViewController.m

#import "ViewController.h"
#import "NewSceneCollectionHeaderView.h"
#import "NewSceneCollectionFooterView.h"
#import "NewSceneCollectionViewCell.h"
@interface ViewController ()
@end
//cell、header、footerView 标识
static NSString *cellIdentifier = @"NewSceneCollectionViewCell";
static NSString *headerIdentifier = @"NewSceneCollectionHeaderView";
static NSString *footerIdentifier = @"NewSceneCollectionFooterView";
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    //创建布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //flowlaout的属性,确定是水平滚动,还是垂直滚动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //接下来就在创建collectionView的时候初始化,就很方便了(能直接带上layout)
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 200, 320, 280) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor grayColor]; 
    //指定数据源和代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //添加到主页面上去 
    [self.view addSubview:self.collectionView];
    //collectionCell的注册
    [self.collectionView registerClass:[NewSceneCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    //collection头视图的注册。  注意:奇葩的地方来了,头视图和尾部视图也得注册
    [self.collectionView registerClass:[NewSceneCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
    [self.collectionView registerClass:[NewSceneCollectionFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:footerIdentifier];
    /*另一种方式
    //从Xib上注册
    UINib *nib = nil;
    nib = [UINib nibWithNibName:cellIdentifier bundle:nil];
    [self.collectionView registerNib:nib
                 forCellWithReuseIdentifier:cellIdentifier];
    //注册headerview和footerview
    nib = [UINib nibWithNibName:headerIdentifier bundle:nil];
    [self.collectionView registerNib:nib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
    nib = [UINib nibWithNibName:footerIdentifier bundle:nil];
    [self.collectionView registerNib:nib forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier];
    */
    [self.view addSubview:self.collectionView];
}
/********************************************************
 *UICollectionViewDataSource/Delegate/DelegateFlowLayout
 ********************************************************/
#pragma mark  UICollectionViewDataSource/Delegate
//返回多少组(section),此方法不写默认是1组(跟tableview类似)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
#pragma mark required
//每组返回多少个Item,这个Item类似tableview中的cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 10;
}
//返回cell,这里构建Item(即cell)
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //这里是自定义的cell
    NewSceneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    return cell;
}
#pragma mark  optional
//自定义header/footerView
// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
//这里返回的view必须要从dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:这个方法中获取,而且根据不同的kind作为headerView或者footerView,切记:collectionView中头部视图和尾部视图也需要注册
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    if (UICollectionElementKindSectionHeader == kind) {
        //这里是自定义的头视图
        NewSceneCollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor whiteColor]; 
        return headerView;
    }
    if (UICollectionElementKindSectionFooter == kind {
        //这里是自定义的尾视图               
        NewSceneCollectionFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerIdentifier forIndexPath:indexPath];
        footerView.backgroundColor = [UIColor whiteColor]; 
        return footerView;
    }
    return reusableView;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//布局确定每个Item 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{    
    return CGSizeMake(100, 100);
}
//布局确定每个section内的Item距离section四周的间距 UIEdgeInsets
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
//返回每个section内上下两个Item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10; 
}
//返回每个section内左右两个Item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
//返回headerView的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGFloat width = CGRectGetWidth(collectionView.bounds);
    CGFloat height = width + 86;
    return CGSizeMake(width, height);
}
//返回footerView的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    CGFloat width = CGRectGetWidth(collectionView.bounds);
    CGFloat height = 144;
    return CGSizeMake(width, height);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewSceneCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];
    NSLog(@"item======%ld",(long)indexPath.item);
    NSLog(@"row=======%ld",(long)indexPath.row);
    NSLog(@"section===%ld",(long)indexPath.section);
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


相关文章
C#学习相关系列之多线程---TaskCompletionSource用法(八)
C#学习相关系列之多线程---TaskCompletionSource用法(八)
1113 0
|
9月前
|
人工智能 Linux API
OpenClaw 全场景命令速查手册:阿里云/本地系统部署+大免费模型api配置+完整命令库整理
2026年,OpenClaw(Clawdbot)已成为最主流的开源AI智能体执行框架,凭借轻量化、可扩展、本地优先、多平台接入等特性,成为个人与团队搭建数字助理的首选工具。但在实际使用中,大量用户面临**命令记不住、部署流程复杂、大模型配置失败、服务无法启动、故障不会排查**等问题,严重影响使用效率。
1276 0
|
9月前
|
人工智能 Linux API
OpenClaw(Clawdbot)简中攻略:阿里云/本地部署+API配置+核心Skill集成及避坑手册
OpenClaw(原Clawdbot)作为开源AI Agent领域的标杆工具,凭借“轻量灵活、功能全面、全平台兼容”的特性,成为个人与团队提升效率的核心选择。但现有教程多分散于不同平台,且缺乏针对中文用户的系统化指南,导致新手常面临“部署难、配置乱、用不精”的问题。
1500 4
|
SQL 弹性计算 关系型数据库
MCP我知道:手搓代码学原理到应用,附讲解视频
MCP火爆异常,目前大量资料介绍了基本概念,与LLM联动这块通常是讲如何集成在Claude、Cursor这些系统,隐藏了其底层细节原理。本文将从0编写client、Server代码、搭建QwQ-32B大模型、接入云数据库,讲解通过联动外围工具来解决LLM“知识茧房”问题。最后总结并展望了MCP未来的发展。
1979 14
MCP我知道:手搓代码学原理到应用,附讲解视频
|
人工智能 安全 JavaScript
全面解读 SonarQube 8.9 LTS 到 2025.4 的特性变化
本文全面解读SonarQube从8.9 LTS到2025.4 LTA的演进历程,涵盖产品线命名简化、发布周期调整、AI赋能的代码分析升级及安全合规强化,重点解析多质量规则模式、AI代码溯源与修复、SCA依赖风险管控等核心特性,助力企业实现高质量交付。
1170 9
|
9月前
|
人工智能 API 开发者
阿里云Coding Plan详细介绍、收费价格及Lite版和Pro版费用清单,2026年最新手动整理
阿里云百炼Coding Plan是AI编程订阅服务,含Lite(首月7.9元)与Pro(首月39.9元)两版,提供Qwen3.5/3-max/3-coder、Kimi K2.5、GLM-4.7等模型调用额度,支持Qwen Code等工具,按月付费、一键接入。
6437 10
|
NoSQL Redis
基于Redis的高可用分布式锁——RedLock
这篇文章介绍了基于Redis的高可用分布式锁RedLock的概念、工作流程、获取和释放锁的方法,以及RedLock相比单机锁在高可用性上的优势,同时指出了其在某些特殊场景下的不足,并提到了ZooKeeper作为另一种实现分布式锁的方案。
1239 2
基于Redis的高可用分布式锁——RedLock
|
人工智能 算法 开发工具
快手封号一般封多久?
一、封禁时长梯度设计原理
|
存储 安全 数据安全/隐私保护
安全升级!Python AES加密实战,为你的代码加上一层神秘保护罩
【8月更文挑战第2天】数据安全至关重要,AES加密作为对称加密的标准之一,因其高效性与灵活性被广泛采用。本文通过实战演示Python中AES的应用,使用pycryptodome库进行安装及加密操作。示例代码展示了生成随机密钥与初始化向量(IV)、对数据进行加密及解密的过程。注意事项包括密钥管理和IV的随机性,以及加密模式的选择。掌握AES加密能有效保护敏感数据,确保信息安全无虞。
837 6
HTTP 协议的请求方法
【10月更文挑战第21天】