TableView与CollectionView的区别
发布日期:2022-02-08 18:03:27 浏览次数:39 分类:技术文章

本文共 1730 字,大约阅读时间需要 5 分钟。

1、遵循协议:

UITableView:

UITableViewDataSource,UITableViewDelegate
UIcollectionView:
UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

2、注册cell:

tableview可以不注册cell

collectionView必须注册cell,否则会崩溃

① UITableView:

[tableView dequeueReusableCellWithIdentifier:]方法创建cell可以不用注册cell, 但是需要考虑cell为空的情况,并做相应处理。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];    if (!cell) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];    }    cell.textLabel.text = @"system cell";    return cell;}

如果使用如下代码创建cell,必须注册cell,否则会crash。

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID" forIndexPath:indexPath];

注:如果注册了cell,则 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中不需要处理cell为空的情况。

② UICollectionView:

需要注册cell,不用处理cell为空的情况。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCollectionViewCell" forIndexPath:indexPath];return cell;}

3、CollectionView特定的属性:

UICollectionViewFlowLayout对象

  • 有sectionInset属性,控制section的上左下右四个方向距离当前CollectionView的偏移量;
  • 有行间距(minimumLineSpacing)和列间距(minimumInteritemSpacing)属性;(itemSize类似于TableView的rowHeight就不赘述了)

开发中可以充分利用sectionInset:

宽为375的屏幕,需要一行显示三个width=100的item,且列间距为0,如何设置?
a> 可以初始化collectionView的时候设置宽度为300;
b >设置sectionInset = UIEdgeInsetsMake(0, 37.5, 0, 37.5);

4、总结:

创建cell时带forIndexPath:的方法需要注册cell;

已经注册过cell,不用判断cell为空。

转载地址:https://blog.csdn.net/Evelynzn/article/details/80222269 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:A* 寻路算法
下一篇:JS与OC交互

发表评论

最新留言

很好
[***.229.124.182]2024年04月01日 13时00分51秒