自定义 UICollectionViewCell 中的小型 UIImage 视图

Small UIImage view in custom UICollectionViewCell

我有 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 class

- (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

cell.imageView,imageView 对象与您在 Interface Builder 的单元格中添加的对象不同。 UICollectionViewCell 具有正在访问的默认大小 UIImageView,您可以通过在界面生成器中链接子类 DBPhotoCollectionViewCell 的 imageView 来访问 collectionView 的 cellForIndexPath 方法中的 customView imageView,您不需要添加 [self.contentView addSubview:self.imageView] ;在设置方法中。

第二种方法是在添加到单元格 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;
}