首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

UICollectionView 根本使用(配合Flickr API)

2013-04-12 
UICollectionView 基本使用(配合Flickr API)在iOS6的新特性中,UICollectionView是最吸引人的新控件之一。有

UICollectionView 基本使用(配合Flickr API)

在iOS6的新特性中,UICollectionView是最吸引人的新控件之一。有了这个,就不需要再去git上面找各种GridView的源码,也不需要自己用UITableView去模拟一个了。

本文主要通过一个demo介绍UICollectionView的基本使用。

首先看下demo完成后的截图

UICollectionView 根本使用(配合Flickr API)

demo的主要组成部分就是上面的UITextField和下面的UICollectionView

这个应用是通过Flickr的API,根据输入的关键词获取图片,并显示在UICollectionView中。

下面开始简单地说明这个demo,一些和collectionView相关性不强的内容,比如Flickr API的调用,我就简单说下就好,最后会给出源码

Storyboard

UICollectionView 根本使用(配合Flickr API)

其中顶部的toolBar和BarButtonItem和这次的demo没什么关系,这次用到的是在search隔壁的UItextField还有下面的绿色部分就是UICollectionView,在Collection里面的那块就是UICollectionViewCell。

熟悉UITableView的同学都这些应该都比较熟悉,都是View+Cell的组合,等会看到UICollectionView的dataSource和Delegate也会觉得很熟悉的。


下面先看看设置Toolbar背景的一段代码



在说UICollectionView之前,需要先说清楚图片的数据是怎么来的。

下面是viewController.m中定义的property


上图,就是调用Flickr的搜索API并传进相应参数之后返回的结果,最底下的stat就是判断请求结果是否成功的标志,数组Photo就是返回的图片的数据,要拿到图片还要再使用Photo中的参数发送另一条请求,详细是哪个API可以自己看源码,我这里不贴出


在图片的右上方可以看到,在选中了UICollectionViewCell之后,右边的Custom Class有个class的地方,原本填的就是默认的UICollectionViewCell,现在我们就修改它为FlickrPhotoCell,在左边的Scence结构图也可以看到Cell已经修改了。

至于要怎么用自己的Cell,在后面说哈,下面说Layout,不同的Layout会让UICollectionView显示不同的效果,我们完全可以自己写Layout,不过因为这是第一次使用,所以我们就用苹果帮我们写好的FlowLayout来做就好了,自定义的等学了再写(我现在也不会....)

因为有UITableView的经验,所以我们知道要让CollectionView显示数据,需要dataSource和Delegate

下面就先让viewController作为UICollectionView的DataSource和Delegate,我这里是直接在storyboard拉的,也可以用代码写。

#pragma mark - UICollectionView Delegate- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{    //select Item}- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{    //deselect item}#pragma mark - UICollectionViewDelegateFlowLayout- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{    NSString *searchTerm = self.searches[indexPath.section];    FlickrPhoto *photo = self.searchResults[searchTerm][indexPath.row];    CGSize retval = photo.thumbnail.size.width > 0 ? photo.thumbnail.size : CGSizeMake(100, 100);    retval.height += 35;    retval.width += 35;    return retval;}-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{    return UIEdgeInsetsMake(50, 20, 50, 20);}

前两个方法就是当Item被选中和选中后放开的响应。

第三个方法就是FlowLayout Delagte中的一个方法,返回每一个Cell的大小,我们这里是根据每张图片的大小,来设定Cell的大小的。

最后一个方法是返回cell之见、header和footer之见的间隔。


好了 这个demo差不多就是这些咯 这个demo是在http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12学的,还有第二个,学完后再写。

源码:UICollectionView demo

热点排行