无法将 UIImageView 的大小调整为 UICollectionViewCell
Unable to resize UIImageView into UICollectionViewCell
在 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;
}
编辑 1:
虽然下面提供的自动布局约束可以正常工作,但请注意 imageView 是作为单元格 xib 的一部分添加的,因此不要添加约束 manually/programmatically 请确保在 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
取决于你的需要:)
希望对您有所帮助
在 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;
}
编辑 1:
虽然下面提供的自动布局约束可以正常工作,但请注意 imageView 是作为单元格 xib 的一部分添加的,因此不要添加约束 manually/programmatically 请确保在 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
取决于你的需要:)
希望对您有所帮助