UICollectionView基础

iOS UICollectionView学习之二,纯代码实现布局,纯代码实现添加Section Header头部视图和 Section Footer尾部视图 iOS UICollectionView学习之二,纯代码实现布局,纯代码实现添加头部视图跟尾部视图,Header和footer 1、首先看下整个Demo的整体结构:如下图 2、直接上代码 1.自定义单元格类----------MyCell.h  里面添加 @interface MyCell : UICollectionViewCell @property(s 阅读详情

初始化部分:

复制代码
UICollectionViewFlowLayout *flowLayout= [[UICollectionViewFlowLayout alloc]init];
self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20, 20, 250, 350) collectionViewLayout:flowLayout];
self.myCollectionView.backgroundColor = [UIColor grayColor];
[self.myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@“myCell"];
self.myCollectionView.delegate = self;
self.myCollectionView.dataSource = self;

[self.view addSubview:self.myCollectionView];
复制代码

 

UICollectionViewLayout

UICollectionViewLayout决定了UICollectionView如何显示在界面上,Apple提供了一个最简单的默认layout对象:UICollectionViewFlowLayout。

Flow Layout是一个Cells的线性布局方案,并具有页面和页脚。其可定制的内容如下:

itemSize属性

设定全局的Cell尺寸,如果想要单独定义某个Cell的尺寸,可以使用下面方法:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

minimumLineSpacing属性

设定全局的行间距,如果想要设定指定区内Cell的最小行距,可以使用下面方法:

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

minimumInteritemSpacing属性

设定全局的Cell间距,如果想要设定指定区内Cell的最小间距,可以使用下面方法:

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;

scrollDirection属性

设定滚动方向,有UICollectionViewScrollDirectionVertical和UICollectionViewScrollDirectionHorizontal两个值。

headerReferenceSize属性与footerReferenceSize属性

设定页眉和页脚的全局尺寸,需要注意的是,根据滚动方向不同,header和footer的width和height中只有一个会起作用。如果要单独设置指定区内的页面和页脚尺寸,可以使用下面方法:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section

sectionInset属性

设定全局的区内边距,如果想要设定指定区的内边距,可以使用下面方法:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;


 

然后需要实现三种类型的委托:UICollectionViewDataSource, UICollectionViewDelagate和UICollectionViewDelegateFlowLayout。

@interface ViewController : UIViewController <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>

因为UICollectionViewDelegateFlowLayout实际上是UICollectionViewDelegate的一个子协议,它继承了UICollectionViewDelegate,所以只需要在声明处写上UICollectionViewDelegateFlowLayout就行了。


 

UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

返回collection view里区(section)的个数,如果没有实现该方法,将默认返回1:

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

返回指定区(section)包含的数据源条目数(number of items),该方法必须实现:

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

 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

返回某个indexPath对应的cell,该方法必须实现:

复制代码
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
    if(indexPath.section==0)
    {
        cell.backgroundColor = [UIColor redColor];
    }
    else if(indexPath.section==1)
    {
        cell.backgroundColor = [UIColor greenColor];
    }
    return cell;
}
复制代码

UICollectionViewCell结构上相对比较简单,由下至上:

  • 首先是cell本身作为容器view
  • 然后是一个大小自动适应整个cell的backgroundView,用作cell平时的背景
  • 再其次是selectedBackgroundView,是cell被选中时的背景
  • 最后是一个contentView,自定义内容应被加在这个view上

 

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

为collection view添加一个补充视图(页眉或页脚)

 

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section

设定页眉的尺寸

 

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section

设定页脚的尺寸

 

- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier

添加页眉和页脚以前需要注册类和标识:


 

添加补充视图的代码示例:

复制代码
[self.myCollectionView registerClass:[MyHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader"];
[self.myCollectionView registerClass:[MyHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwHeader"];

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {240,25};
    return size;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    CGSize size = {240,25};
    return size;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    MyHeadView *headView;
    
    if([kind isEqual:UICollectionElementKindSectionHeader])
    {
         headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader" forIndexPath:indexPath];
        [headView setLabelText:[NSString stringWithFormat:@"section %d's header",indexPath.section]];
    }
    else if([kind isEqual:UICollectionElementKindSectionFooter])
    {
        headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwHeader" forIndexPath:indexPath];
        [headView setLabelText:[NSString stringWithFormat:@"section %d's footer",indexPath.section]];
    }
    return headView;
}
复制代码

 

MyHeadView.h

#import <UIKit/UIKit.h>

@interface MyHeadView : UICollectionReusableView
- (void) setLabelText:(NSString *)text;
@end

 

MyHeadView.m

复制代码
#import "MyHeadView.h"

@interface MyHeadView()

@property (strong, nonatomic) UILabel *label;

@end

@implementation MyHeadView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.label = [[UILabel alloc] init];
        self.label.font = [UIFont systemFontOfSize:18];
        [self addSubview:self.label];
    }
    return self;
}

- (void) setLabelText:(NSString *)text
{
    self.label.text = text;
    [self.label sizeToFit];
}

@end
复制代码

 

在注册Cell和补充视图时,也可以用新建xib文件的方式:

[self.myCollectionView registerNib:[UINib nibWithNibName:@"MyCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"hxwCell"];

[self.myCollectionView registerNib:[UINib nibWithNibName:@"MySupplementaryView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader"];
    
[self.myCollectionView registerNib:[UINib nibWithNibName:@"MySupplementaryView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwFooter"];

用这种方式注册后,甚至可以不用新建类去绑定这个xib,直接通过viewWithTag的方式获取xib里的控件:

UICollectionReusableView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :kind withReuseIdentifier:@"hxwHeader" forIndexPath:indexPath];

UILabel *label = (UILabel *)[view viewWithTag:1];

label.text = @"empty";

 


 

UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

设定指定Cell的尺寸

复制代码
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section==0 && indexPath.row==1)
    {
        return CGSizeMake(50, 50);
    }
    else
    {
        return CGSizeMake(75, 30);
    }
}
复制代码

 

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;

设定collectionView(指定区)的边距

复制代码
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if(section==0)
    {
        return UIEdgeInsetsMake(35, 25, 15, 25);
    }
    else
    {
        return UIEdgeInsetsMake(15, 15, 15, 15);
    }
}
复制代码

 

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

设定指定区内Cell的最小行距,也可以直接设置UICollectionViewFlowLayout的minimumLineSpacing属性

复制代码
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if(section==0)
    {
        return 10.0;
    }
    else
    {
        return 20.0;
    }
}
复制代码

 

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;

设定指定区内Cell的最小间距,也可以直接设置UICollectionViewFlowLayout的minimumInteritemSpacing属性

复制代码
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if(section==0)
    {
        return 10.0;
    }
    else
    {
        return 20.0;
    }
}
复制代码

 


UICollectionViewDelegate

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

当指定indexPath处的item被选择时触发

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.myArray removeObjectAtIndex:indexPath.row];

[collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
}

P.s. 当你删除或添加元素时,一定要更新numberOfItemsInSection的返回情况。

 

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath

当指定indexPath处的item被取消选择时触发,仅在允许多选时被调用

 

下面是三个和高亮有关的方法:

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath

 

事件的处理顺序如下:

  1. 手指按下
  2. shouldHighlightItemAtIndexPath (如果返回YES则向下执行,否则执行到这里为止)
  3. didHighlightItemAtIndexPath (高亮)
  4. 手指松开
  5. didUnhighlightItemAtIndexPath (取消高亮)
  6. shouldSelectItemAtIndexPath (如果返回YES则向下执行,否则执行到这里为止)
  7. didSelectItemAtIndexPath (执行选择事件)

如果只是简单实现点击后cell改变显示状态,只需要在cellForItemAtIndexPath方法里返回cell时,指定cell的selectedBackgroundView:

复制代码
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
    
    UIView* selectedBGView = [[UIView alloc] initWithFrame:cell.bounds];
    selectedBGView.backgroundColor = [UIColor blueColor];
    cell.selectedBackgroundView = selectedBGView;
    
    return cell;
}
复制代码

如果要实现点击时(手指未松开)的显示状态与点击后(手指松开)的显示状态,则需要通过上面提到的方法来实现:

复制代码
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)colView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [colView cellForItemAtIndexPath:indexPath];
    
    [cell setBackgroundColor:[UIColor purpleColor]];
}

- (void)collectionView:(UICollectionView *)colView  didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [colView cellForItemAtIndexPath:indexPath];
    
    [cell setBackgroundColor:[UIColor yellowColor]];
}
复制代码
Swift UICollectionView 入门指南 如果需要自定义布局,可以创建一个自定义的 UICollectionViewLayout 子类,并将其分配给 collectionView 的 collectionViewLayout 属性。注意:为了使集合视图正常工作,还需要确保正确实现 UICollectionViewDataSource 和 UICollectionViewDelegate 协议中的其他方法,并根据需要自定义单元格的外观和行为。在自定义布局的示例中,我们需要重写几个关键方法来计算和设置单元格的位置和布局。步骤3:处理用户交互。 阅读详情

相关推荐

Web前端开发技术:实验14-16

实验14 1. 编写JavaScript程序实现“九九乘法口诀”表,如图14-40所示。 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>九九乘法表</title> </head> <body> <h1>九九乘法表</h1> </body> <scri

KslgmrDry的博客 1万+

iOS开发实战——CollectionView中cell的间距设置

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34413357的博客 1549

Camera(5)metadata

Metadata 是整个 Android camera 中类似于高楼大厦中的管道系统一样,贯穿了整个 Camera 的 Framework 和 vendor HAL。Metadata 里面包含了所有的控制、参数、返回值等等。Metadata分为Android原生的Metadata和芯片商或者用户自定义的Metadata,即Android Tag和Vendor Tag。Vendor Tag在Hal中定义,并在camx和chi目录中使用。

qq_55893245的博客 3057

【iOS开发】—— UICollectionView的介绍

UICollectionView的简单学习

weixin_50990189的博客 5895

Arm Neoverse CMN-700 SLC内存系统与缓存分区技术解析

现代处理器架构中,缓存一致性协议与内存子系统设计直接影响系统性能。Arm Neoverse CMN-700采用的SLC(System Level Cache)通过16-way组相联设计实现高效数据缓存,其物理地址索引机制支持灵活的way分区配置。在软件可配置内存(OCM)模式下,SLC可作为独立内存空间使用,通过寄存器控制实现模式切换与区域锁定。缓存分区技术则通过请求源分类和way-based分配策略,满足实时性任务与吞吐量场景的不同需求。这些技术在5G基站、边缘计算等低延迟场景中具有重要应用价值,特别是C

weixin_30263073的博客 625

DC/DC开关电源学习笔记(十三)Buck-Boost升降压电路工作原理

Buck-Boost电路是一种能够实现输出电压高于或低于输入电压的DC-DC变换器,且输出电压极性与输入电压相反。它结合了Buck(降压)和Boost(升压)两种拓扑的特点,广泛应用于需要灵活电压调整的场合,如电池供电设备、LED驱动和工业控制系统。本文将从电路结构、工作原理、关键公式推导及实际应用等方面进行详细分析。

小幽余生不加糖 3508

【iOS】—— UICollectionView基础

一、UICollectionView基础: 1.简介: UICollectionView是iOS6之后引入的一个新的UI控件,在目前的iOS开发中,使用非常广泛。它和UITableView都继承自UIScrollView,但是它比UITableView更加强大,可以根据需要自定义各种各样复杂的布局。 它和UITableView十分相似,并且很多代理方法都十分类,具体的可以看看苹果官方的文档:UICollectionView - Apple Developer 2.特点: (1)系统自带的流水布局支持水平和垂

m0_55124878的博客 5110

[计算机头歌]爬虫进阶

【代码】爬虫进阶。

M_inherit的博客 922

UICollectionView的基础用法

UICollectionView的基础用法UICollectionView类似UITableView,我们对UITableView很熟悉,可以类比tableView学习。类比而已,肯定有不同之处了。UICollectionView继承UIScrollView,有两个代理方法和一个UICollectionViewDelegateFlowLayout,今天不讲UICollectionViewDelega

文明的博客 3317

Google Earth Engine:LandTrendr (Landsat Collection 2)全更新使用(代码调用+UI交互)

本文介绍了使用Landsat Collection 2进行连续变化监测的分析方法,包含代码实现和可视化界面两部分。代码部分通过Google Earth Engine平台运行LandTrendr算法,设置参数包括时间范围、光谱指数、变化检测阈值等,最终生成变化幅度和检测年份的可视化图层,并将结果导出至Google Drive。可视化界面部分展示了基于LandTrendr的土地覆盖变化结果,结合Landsat影像进行分析。整个方法实现了从数据处理到结果展示的完整流程,适用于森林覆盖等环境变化监测。

此星光明博客 212

**YOLOv11性能突破:基于YOLOv10-PSA注意力机制的目标检测革命性升级**

购买即可解锁300+YOLO优化文章,并且还有海量深度学习复现项目,价格仅需两杯奶茶的钱,别人有的本专栏也有!

m0_71589036的博客 199

UICollectionView基础API笔记

UICollectionView系列API,属性含义笔记。在UICollectionView笔记1中我们了解了UICollectionView是什么,以及可以做什么;在UICollectionView笔记2中我们了解了UICollectionViewLayout相关内容。这一篇我们就UICollectionView相关API做一个整体的了解。   一、UICollectionView  

mark_stray 537

31、自然语言生成中的流畅度评估

本博客探讨了自然语言生成(NLG)中流畅度评估的重要性和方法。文章详细介绍了流畅度的定义及其影响因素,包括句法结构、词汇选择、语义一致性和段落组织。同时,讨论了自动评估和人工评估两种主要方法,并以机器翻译、自动摘要和对话系统为例分析了流畅度评估的应用场景。最后,文章提出了提升流畅度的技术策略以及未来研究方向,为相关领域的研究者和开发者提供了有价值的参考。

h9j8k7l6m5n的博客 275

UICollectionView 基础全面解析

大家好,我叫mark qq:1124728522 欢迎大家多多交流 批评指正

iOS_mark的博客 2万+

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

UICollectionView 基础

在iOS开发中经常会用到UICollectionView,和UITableView同样即成UIScrollView 但是操作起来比UITableVIew要麻烦一些 ,有些地方需要注意,一下是UICollectionView基础详解。 // // ViewController.m // Collection #import "ViewContro...

dfgwang1202的博客 128

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

上一篇: 全面了解 iOS 静态库开发
下一篇: [ReactiveCocoa](翻译|巨坑)Basic Operators基本操作
celljay
博客等级 码龄15年 1粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值