collectionView的案例
- #import "ViewController.h"
- #import "CollectionViewCell.h"
- @interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
- @property (weak, nonatomic) IBOutlet UICollectionView *collectionCell;
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- self.collectionCell.backgroundColor = [UIColor greenColor];
- self.collectionCell.dataSource = self;
- self.collectionCell.delegate = self;
- }
- #pragma mark -- UICollectionViewDataSource
- //设置collectionCell的个数
- -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
- {
- return 9;
- }
- //定义展示的Section的个数
- -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
- {
- return 1;
- }
- //每个UICollectionView展示的内容
- -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- //使用collectionCell进行注册,通过xib文件加载视图
- [self.collectionCell registerNib:[UINib nibWithNibName:@"myCell" bundle:nil]
- forCellWithReuseIdentifier:@"mycell"];
- CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"mycell" forIndexPath:indexPath];
- //图片名称
- NSString *imageToLoad = [NSString stringWithFormat:@"%ld.jpg", indexPath.row];
- //加载图片
- cell.iamgeView.image = [UIImage imageNamed:imageToLoad];
- //设置label文字
- cell.labeiInfo.text = [NSString stringWithFormat:@"image%ld",indexPath.row];
- return cell;
- }
- //设置每个各自的大小
- -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return CGSizeMake(170, 170);
- }
- //定义每个UICollectionView 的 margin
- -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
- {
- return UIEdgeInsetsMake(5, 5, 5, 5);
- }
- //UICollectionView被选中时调用的方法
- -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
- cell.backgroundColor = [UIColor whiteColor];
- }
- //返回这个UICollectionView是否可以被选择
- -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return YES;
- }
- //隐藏状态栏
- -(BOOL)prefersStatusBarHidden
- {
- return YES;
- }
- @end
程序运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具