IOS开发学习分享(一)——StoryBoard的UICollectionView和UINavigationView的使用

本文详细介绍了如何在iOS应用中使用UICollectionView来实现动态数据展示。包括UICollectionView的基本配置、UICollectionViewCell的定义及显示、数据源设置等关键步骤,并分享了一些开发过程中遇到的问题及解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先贴一下CollectionView的结构图
结构图


一、UICollectionView和UINavigationView构成

1.Xcode的storyboard开发十分的方便,新建一个UICollectionView可以直接通过上图右下角的组件直接拖拽得到。
2.UINavigationView的添加也是十分的简单,如图:
这里写图片描述
选中UICollectionView的Scene,然后点击Navigation Controller就可以了。
3.UICollectionViewCell的添加也可以通过右下角的组件拖拽形成。
4.接下来就是controller层和view层的结合了。通过storyboard定义的视图模板,要实现数据的动态展示,就需要自定义的controller辅助。
这里写图片描述
这里要注意的是Inherit Module From Target这个选项最好不要选,否则可能会导致自定义的类找不到而报错。。。


先贴一下博主的controller的代码(删减了业务相关的代码)

头文件

@interface ClassifyController : UICollectionViewController <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,NSURLSessionDataDelegate>
@property (strong, nonatomic)
IBOutletCollection(UICollectionView) NSArray *collection;
//视频分类的id
@property(nonatomic,readwrite) NSArray *categories;
//网络得到的数据
@property(nonatomic,readwrite) NSMutableData *result;
@end

实现

@implementation ClassifyController
static NSString * CellIdentifier = @"cell";

- (void)viewDidLoad {
    _categories = [NSArray new];
    _result = [NSMutableData new];
    [super viewDidLoad];
}

//定义展示的cell的数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _categories.count;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//这里使用的是自定义的cell
    ClassifyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    return cell;
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//cell的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  ..........
}

下面说一下博主遇到的一些坑。

  • Cell的显示,在storyboard定义的cell,如果你不是想弄多种不同格式的cell,那么是需要拖拽一个cell,这里十分重要的一件事情是,必须给cell指定一个identifier,名字自己随意起,如果不指定的话cell是不会显示的。这里写图片描述
  • 由于博主是想做动态的数据展示,所以cell的数目是动态变化的,实现方案从网上找到的大多数都是在controller里面定义一个数组,然后根据数组的长度定义cell的数目。
  • 而关于cell视图的刷新,由于博主是异步的读取数据,刷新的时候不是在UI的主线程里,所以需要使用这样的代码刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
    });

这里的self.collectionView也是一个需要注意的地方,在storyboard开发里面,有一个叫Referencing Outlet CollectionsReferencing Outlets的东西,具体就是在视图编辑里面右键就可以看到了。关于这两个东西的区别和作用,网上很多。
这里要注意的是,collectionView是绑定了UICllectionView的Referencing Outlet Collections,博主开发的时候使用Referencing Outlets会报错。。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值