我有UICollectionViewCell
#import "DBPhotoCollectionViewCell.h"
#define IMAGEVIEW_BORDER_LENGTH 5
@implementation DBPhotoCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self setup];
}
return self;
}
/* Need to implement the initWithCoder method since this class will be created from the storyboard */
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self){
[self setup];
}
return self;
}
/* Create the UIImageView and add it to the cell's contentView in code. */
-(void)setup
{
self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(self.bounds, IMAGEVIEW_BORDER_LENGTH, IMAGEVIEW_BORDER_LENGTH)];
[self.contentView addSubview:self.imageView];
}
@end
从CollectionViewController类调用此Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Photo Cell";
DBPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
cell.imageView.image = [UIImage imageNamed:@"Astronaut.jpg"];
// Configure the cell
return cell;
}
但是当我启动应用程序时,我遇到一个问题,我的图片显示的是小尺寸。我错过了什么?
http://screencast.com/t/ia8tE05P6yc http://screencast.com/t/33N4AhT7
答案 0 :(得分:0)
cell.imageView,imageView对象与您在Interface Builder的单元格上添加的对象不同。 UICollectionViewCell具有正在访问的默认大小UIImageView,您可以通过在界面构建器中链接subClass DBPhotoCollectionViewCell的imageView来访问collectionView的cellForIndexPath方法中的customView imageView,您不需要添加[self.contentView addSubview:self.imageView];在设置方法。
当您添加到cell contentView
时,第二种方法是为imageView分配标记值/* Create the UIImageView and add it to the cell's contentView in code. */
-(void)setup
{
self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(self.bounds, IMAGEVIEW_BORDER_LENGTH, IMAGEVIEW_BORDER_LENGTH)];
self.imageView.tag=1;
[self.contentView addSubview:self.imageView];
}
//And access imagView in cellForIndexPath
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Photo Cell";
DBPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
UIImageView *imageView=[cell.contentView viewWithTag:1];
imageView.image = [UIImage imageNamed:@"Astronaut.jpg"];
// Configure the cell
return cell;
}