源码

首页 » 归档 » 源码 » UICollectionView代码创建.以及和 TableView 的区别-ios学习从入门到精通尽在姬长信

UICollectionView代码创建.以及和 TableView 的区别-ios学习从入门到精通尽在姬长信

分享最热门的资讯

原文

UICollectionView代码创建

简介:

UICollectionView是UIScrollView的子类,显示一组 UICollectionCell 或其子类

UICollectionViewController有数据源,委托 (UICollectionViewDelegate),布局类

1.数据源:UICollectionViewController.返回几行几列等方法

2.委托:UICollectionViewDelegate,哪一列被点击打等方法.

3.布局类:为每个 Cell 布局,如果想按网格布局,则可以使用 UICollectionViewFlowLayout,如果想自定义布局,可以创建 UICollectionViewLayout 的自定义子类.

UICollectionViewCell的 contentView 默认是没有子试图的,所以需要自定义 创建UICollectionViewCell的子类,来添加你想用来显示的东西

创建步骤

网上很多教程都直接在 ViewDidLoad 中创建,但是好像并没什么用,具体细节还有待深究,我的做法是直接将 ViewController 的 view 设置为 CollectionView(创建 UICollectionViewController 文件,并且设置为原始 viewController 的类)

1.声明一个全局变量 UICollectionView *coll,在 loadView 创建 UICollectionView,和 UICollectionViewFlowOut

 - (void)loadView
 {
  UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
 _coll = [[UICollectionView alloc] initWithFrame:CGRectMake(0,   0, 500, 500) collectionViewLayout:layout];
 self.view = _coll;
 _coll.backgroundColor = [UIColor whiteColor];
   }

2.viewDidLoad 中注册 Cell ,以便重用,并且设置数据源和 DataSource代理为自己

- (void)viewDidLoad {
[super viewDidLoad];

_coll.delegate = self;
_coll.dataSource = self;

// Register cell classes
[_coll registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

// Do any additional setup after loading the view.

3.设置数据源

#pragma mark - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 4;
}
//注册 Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

cell.backgroundColor = [UIColor blueColor];

return cell;

4.布局可以实现在FlowOut 协议中的方法来设置 item 大小,外边距等,这个可以看下文档实现,到这里基本的代码构建就完成了

UICollectionView 和 UITableView 的不同之处

1.最大的不同在于,UITableView 只显示UITableViewCell 一列,而 UICollectionView 可以任意安排 UICollectionCell

2.UICollectionCell 的 contentView 没有子试图,需要自定义,UITableViewCell 可以用默认的

其他倒是都差不多

ios学习从入门到精通尽在姬长信

(0)

本文由 姬長信 创作,文章地址:https://blog.isoyu.com/archives/2166.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:5月 5, 2017 at 04:59 下午

热评文章

发表回复

[必填]

我是人?

提交后请等待三秒以免造成未提交成功和重复