iOS UICollectionView 入门 04 使用UICollectionView的准备工作

使用UICollectionView和使用UITableView类似,需要为它们设置用于数据显示的事件处理的data source和delegate。

修改ViewController.m的@Interface声明,表明我们的类遵循UICollectionViewDelegate和UICollectionViewDataSource协议:

@interface ViewController () <UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource>实现协议:

UICollectionViewDataSource

#pragma mark – UICollectionView Data Source- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{NSString *searchItem = self.searchs[section];return [self.searchResults[searchItem] count];}返回指定section中要显示的cell数。本程序中,每个关键字的搜索结果对应一个section。

– (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{return [self.searchs count];}返回section的数量。

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FlickrCell" forIndexPath:indexPath];cell.backgroundColor = [UIColor whiteColor];return cell;}返回指定下标对应的cell。

UICollectionViewDelegate

暂时是空的实现:

#pragma mark – UICollectionViewDelegate- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{}- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{}UICollectionViewFlowLayoutDelegate

返回cell的大小,首先获取cell对应的相片,然看其缩略图的尺寸。

#pragma makr – UICollectionViewDelegateFlowLayout- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{NSString *searchItem = self.searchs[indexPath.section];FlickrPhoto *photo = self.searchResults[searchItem][indexPath.row];CGSize retval = photo.thumbnail.size.width > 0 ? photo.thumbnail.size : CGSizeMake(100, 100);retval.height += 35;retval.width += 35;return retval;}返回cell之间间距包括header和footer

– (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{return UIEdgeInsetsMake(50, 20, 50, 20);}

添加UICollectionView到ViewController

添加outlet:

@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;通过storyboard添加UICollectionView

设置collection view的背景色为透明,通过ctrl+drag的方式,为collection view设置data source和delegate,连接collection view和outlet。修改viewDidLoad,,注册UICollectionViewCell:

[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"FlickrCell"];修改textFieldShouldReturn方法,用reloadData替换 // placeholder: reload collection view data:

[self.collectionView reloadData];编译运行,恭喜你,你的CollectionView已经可以用搜索结果的图片大小来显示白色的站位图了:

下一节,我们创建自己的UICollectionViewCell来显示真实搜索结果的缩略图。转载请注明出处:

真正的停下来,享受自我的体验时刻,也许浮光掠影,

iOS UICollectionView 入门 04 使用UICollectionView的准备工作

相关文章:

你感兴趣的文章:

标签云: