ios UICollectionView使用自定义UICollectionViewCell

news/2025/2/22 15:25:07

和UITableView用法类似,UITableView主要是显示按行排列的数据,UICollectionView则用在显示多行多列的数据,今天我们继续来实现app下载页面的效果。

1.先自定义UICollectionViewCell,一个cell就相当于列表中的一项了。

记得勾上,这样就自动创建xib组件了

按住ctrl,鼠标连线到AppCollectionView.h文件,定义好属性

AppCollectionViewCell.h

//
//  AppCollectionViewCell.h
//  iosstudy2024
//
//  Created by figo on 2025/2/18.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface AppCollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *appImg;
@property (weak, nonatomic) IBOutlet UILabel *appName;
@property (weak, nonatomic) IBOutlet UIButton *btnDownload;

@end

NS_ASSUME_NONNULL_END

AppCollectionViewCell.m

//
//  AppCollectionViewCell.m
//  iosstudy2024
//
//  Created by figo on 2025/2/18.
//

#import "AppCollectionViewCell.h"

@implementation AppCollectionViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

@end

2.创建控制器AppsDownViewController

AppsDownViewController.h

//
//  AppsDownViewController.h
//  iosstudy2024
//
//  Created by figo on 2025/2/18.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface AppsDownViewController : UIViewController

@end

NS_ASSUME_NONNULL_END

AppsDownViewController.m

//
//  AppsDownViewController.m
//  iosstudy2024
//
//  Created by figo on 2025/2/18.
//
#import "AppCollectionViewCell.h"
#import "AppsDownViewController.h"

@interface AppsDownViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *appUICollectionView;

@end

@implementation AppsDownViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.appUICollectionView.delegate = self;
    self.appUICollectionView.dataSource = self;
    //关联自定义AppCollectionViewCell到当前页面的UICollectionView
    UINib * nib=[UINib nibWithNibName:@"AppCollectionViewCell" bundle:nil];
    [self.appUICollectionView registerNib:nib forCellWithReuseIdentifier:@"testCell"];
    //设置布局格式
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

//    CGFloat w=(UIScreen.mainScreen.bounds.size.width-3*30)/2;
    layout.itemSize=CGSizeMake(101, 135);
//    layout.minimumLineSpacing=5;
//    layout.minimumInteritemSpacing=5;
//    layout.sectionInset=UIEdgeInsetsMake(0, 5, 0, 5);
    self.appUICollectionView.collectionViewLayout=layout;
    self.appUICollectionView.backgroundColor=[UIColor blueColor];
}


//每一项collectionViewCell
- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    AppCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"testCell" forIndexPath:indexPath];
    
    //使用tag传参@"APPName"+indexPath.item;
    cell.appName.text=[NSString stringWithFormat:@"APPName%ld",indexPath.item];
    NSString *imgPath=[[NSBundle mainBundle]pathForResource:@"star" ofType:@".png"];
    //照片拖入Assets件夹会找不到资源,注意需要项目下新建group命名为Supporting Files,再项目外新建文件夹比如icons,然后将图片放入icons,再将icons文件夹拖入Supporting Files才能找到,否则返回nil
    UIImage *uiImage=[UIImage imageWithContentsOfFile:imgPath];
    cell.appImg.image=uiImage;
    cell.btnDownload.tag=indexPath.item;
    //给按钮添加事件
    [cell.btnDownload addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];



    return cell;
}
-(void)btnClick:(UIButton *) btn  {
    
    NSLog(@"Selected item at index %ld", btn.tag);
}

//选中某一项
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"didSelectItemAtIndexPath %ld", (long)indexPath.item);
}

//每个Section里面有多少项
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 12;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
@end

xib文件,就放了一个UICollectionView

3.SceneDelegate.m设置运行当前controller

//
//  SceneDelegate.m
//  iosstudy2024
//
//  Created by figo on 2024/8/5.
//

#import "SceneDelegate.h"
//#import "WidgetViewController.h"
//#import "TableViewTestViewController.h"
//#import "TableViewAddressBookViewController.h"
#import "NewsViewController.h"
#import "UICollectionViewTestController.h"
#import "AppDownloadViewController.h"
#import "AppsDownViewController.h"
@interface SceneDelegate ()

@end

@implementation SceneDelegate


- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
 
    
    
        AppsDownViewController * viewController = [[AppsDownViewController alloc]init];
        self.window.rootViewController=viewController;
}


- (void)sceneDidDisconnect:(UIScene *)scene {
    // Called as the scene is being released by the system.
    // This occurs shortly after the scene enters the background, or when its session is discarded.
    // Release any resources associated with this scene that can be re-created the next time the scene connects.
    // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}


- (void)sceneDidBecomeActive:(UIScene *)scene {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    NSLog(@"%s",__func__);

}


- (void)sceneWillResignActive:(UIScene *)scene {
    // Called when the scene will move from an active state to an inactive state.
    // This may occur due to temporary interruptions (ex. an incoming phone call).
    NSLog(@"%s",__func__);
}


- (void)sceneWillEnterForeground:(UIScene *)scene {
    // Called as the scene transitions from the background to the foreground.
    // Use this method to undo the changes made on entering the background.
    NSLog(@"%s",__func__);
}


- (void)sceneDidEnterBackground:(UIScene *)scene {
    // Called as the scene transitions from the foreground to the background.
    // Use this method to save data, release shared resources, and store enough scene-specific state information
    // to restore the scene back to its current state.
    NSLog(@"%s",__func__);
}


@end


http://www.niftyadmin.cn/n/5862447.html

相关文章

算法专题(四):前缀和

目录 刷题汇总&#xff1a;传送门&#xff01; 一、【模板】前缀和 1.1 题目 1.2 思路 1.3 代码实现 二、【模板】二维前缀和 2.1 题目 2.2 思路 2.3 代码实现 三、寻找数组的中心下标 3.1 题目 3.2 思路 3.3 代码实现 四、 除自身以外数组的乘积 4.1 题目 4…

Spring MVC的基本概念

1. Spring MVC 的核心概念 Spring MVC 是基于 MVC 设计模式的框架&#xff0c;其核心组件包括&#xff1a; Controller&#xff08;控制器&#xff09;&#xff1a;接收用户请求&#xff0c;处理业务逻辑&#xff0c;并返回视图名称或数据。 Model&#xff08;模型&#xff0…

内核数据结构用法(5)hlist

hlist hlist&#xff08;哈希链表&#xff09;是一种在 Linux 内核中使用的链表结构&#xff0c;主要用于实现哈希表。它是一种轻量级的数据结构&#xff0c;适用于需要高效插入和删除操作的场景。以下是对 hlist 的详细介绍及用法。 hlist 的结构 在 Linux 内核中&#xff…

图论 之 迪斯科特拉算法求解最短路径

文章目录 题目743.网络延迟时间3341.到达最后一个房间的最少时间I 求解最短路径的问题&#xff0c;分为使用BFS和使用迪斯科特拉算法&#xff0c;这两种算法求解的范围是有区别的 BFS适合求解&#xff0c;边的权值都是1的图中的最短路径的问题 图论 之 BFS迪斯科特拉算法适合求…

Linux自学day24-进程和线程2

一 进程结束 这段代码的主要功能是创建一个子进程&#xff0c;子进程休眠 10 秒后以退出状态码 10 结束&#xff0c;父进程等待子进程结束并回收其资源&#xff0c;同时根据子进程的退出状态输出相应的信息。 int main(int argc, const char **argv) {// 定义一个 pid_t 类…

飞书API

extend目录下,API <?php // ---------------------------------------------------------------------- // | 飞书API // ---------------------------------------------------------------------- // | COPYRIGHT (C) 2021 http://www.jeoshi.com All rights reserved. …

电商API安全防护:JWT令牌与XSS防御实战

在电商 API 的安全防护中&#xff0c;JWT&#xff08;JSON Web Token&#xff09;令牌用于身份验证和授权&#xff0c;而 XSS&#xff08;跨站脚本攻击&#xff09;防御则是防止恶意脚本注入&#xff0c;保护用户数据和系统安全。以下是这两方面的实战介绍。 JWT 令牌实战 1. 生…

flowable适配达梦数据库

文章目录 适配相关问题无法从数据库产品名称“DM DBMS”中推断数据库类型分析解决 构建ibatis SqlSessionFactory时出错&#xff1a;inStream参数为null分析解决 liquibase相关问题问题一&#xff1a;不支持的数据库 Error executing SQL call current_schema: 无法解析的成员访…