iOS UICollectionView 入门 05 创设自定义UICollectionViewCell
iOS UICollectionView 入门 05 创建自定义UICollectionViewCell
默认情况下,除了改变背景色,UICollectionViewCell不允许我们进行太多的配置。我们需要创建UICollectionViewCell的子类来实现对cell的配置。
创建名为FlickrPhotoCell的类,继承于UICollectionViewCell。
修改FlickrPhotoCell.h,为cell创建imageView outlet和photo指针。
@class FlickrPhoto; @interface FlickrPhotoCell : UICollectionViewCell @property (nonatomic, strong) IBOutlet UIImageView *imageView; @property (nonatomic, strong) FlickrPhoto *photo; @end打开storyboard,选中CollectionView中的CollectionViewCell,我们需要设置这个cell的类和identifier:
拖拽cell到接近300x300大小。
添加一个image view到cell中,居中填满整个cell:
设置image view的填充方式为Aspect Fill。
连接imageView到cell的outlet。
最后我们为view的顶部添加图钉。
接下来,我们修改代码,使用新创建的FlickrPhotoCell:
返回FlickrPhotoCell而不是UICollectionViewCell并未cell设置photo:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { FlickrPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FlickrCell" forIndexPath:indexPath]; NSString *searchTerm = self.searchs[indexPath.section]; cell.photo = self.searchResults[searchTerm][indexPath.row]; return cell; }
从viewDidLoad中移除cell注册方法:
//[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"FlickrCell"];重载setter方法,修改FlickrPhotoCell.m:
#import "FlickrPhoto.h" #import <QuartzCore/QuartzCore.h>
@implementation FlickrPhotoCell - (void)setPhoto:(FlickrPhoto *)photo { if (_photo != photo) { _photo = photo; } self.imageView.image = _photo.thumbnail; } @end编译,执行,图片缩略图被显示到UICollectionView上了:
下一节,我们将使用UICollectionReusableView来创建一个标题栏。
转载请注明出处:http://blog.****.net/yamingwu/article/details/44316919