【问题标题】:Unable to resize UIImageView into UICollectionViewCell无法将 UIImageView 大小调整为 UICollectionViewCell
【发布时间】:2018-08-20 06:22:19
【问题描述】:

在 iOS 应用程序中,我有一个 UICollectionView 显示图片网格。但是我无法精确设置每个 UICollectionViewCell 中包含的 UIImageView 的大小。所有都在 Interface Builder 中定义。

正如我们在下图中看到的,不仅每张图片的大小不一样(代码显示它应该对所有人都固定),而且它们与我的 setFrame 值不匹配。 尝试应用其他帖子的建议,但问题保持不变。

如何为 UIImageView 设置固定大小?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"backgroundCell" forIndexPath:indexPath];

    UIImageView *imageView = (UIImageView *)[cell viewWithTag:110];
    imageView.image=[UIImage imageNamed:[allImages objectAtIndex:indexPath.row]];
    imageView.translatesAutoresizingMaskIntoConstraints=YES;
    imageView.frame=CGRectMake(10,10, 50, 200);
    cell.backgroundColor=[UIColor redColor];
    return cell;
}

【问题讨论】:

    标签: ios objective-c uicollectionview uiimageview


    【解决方案1】:

    编辑 1:

    虽然下面提供的自动布局约束可以正常工作,但请注意 imageView 是作为单元格的 xib 的一部分添加的,所以不要手动/以编程方式添加约束,请确保在 xib 中应用相同的约束

    尝试设置自动布局约束,如下所示

        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.leftAnchor.constraint(equalTo: cell.leftAnchor).isActive = true
        imageView.rightAnchor.constraint(equalTo: cell.rightAnchor).isActive = true
        imageView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
        imageView.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true
    

    最后,尝试修改图像视图的内容模式

    imageView.contentMode = .scaleAspectFit/.scaleAspectFill 取决于您的需要:)

    希望对你有帮助

    【讨论】:

    • 成功了,谢谢!我也必须将 Clip 添加到 Bounds 以获得更好的结果。
    • @laurent-crivello : 很高兴它成功了 :) 编码愉快
    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多