【问题标题】:How do I initialize a custom UICollectionViewCell with a UIImageView that fills the cell?如何使用填充单元格的 UIImageView 初始化自定义 UICollectionViewCell?
【发布时间】:2014-04-27 22:32:37
【问题描述】:

我正在尝试使用自定义 UICollectionViewCells 实现侧滚动 UICollectionView。每个自定义单元格都包含一个应该填充单元格的 UIImageView。现在我正在像这样设置 UIImageView 的大小,

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

static NSString *cellID = @"cellID";
THCVCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath]; 
cell.imageView.image = [self.images objectAtIndex:(indexPath.row % [self.images count])];
cell.imageView.frame = cell.bounds;

return cell;  
}

但 UIImageView 不会填充单元格,直到单元格出列以供重用。

我应该改变什么以使 UIImageView 在单元格首次显示时显示为应有的样子?

【问题讨论】:

    标签: ios uicollectionview uicollectionviewcell


    【解决方案1】:

    如果在THCVCell.m 内部,您添加了如下内容:

    - (void) layoutSubviews {
        _imageView.frame = self.contentView.bounds;
    }
    

    这样,如果单元格改变大小,imageView 会适应。

    然后删除:

    cell.imageView.frame = cell.bounds;
    

    【讨论】:

    • 谢谢洛根!这是一个快速修复。我的应用现在运行良好。
    • 很高兴听到它的工作,祝你项目的其余部分好运!
    【解决方案2】:

    尝试以下操作,这将使 imageView 随单元格调整大小而调整。

    -(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"cellID";
    THCVCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath]; 
    cell.imageView.image = [self.images objectAtIndex:(indexPath.row % [self.images count])];
    cell.imageView.frame = cell.contentView.bounds;
    cell.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    
    return cell;  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多