我有一个 UICollectionView,每个 UICollectionViewCell 都是一个带有 UIImageView 的自定义类
@interface MyCollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *image;
@end
然后我有一个图像,我想放在 ImageView 中。但我无法让图像正确适合 ImageView 。这是图像。 这些是确切的尺寸,我认为那是 36x36,但本质上我不希望大小很重要我只是希望它按比例缩小并适合而不管大小。 Storyboard中 UIImageView 的尺寸为 59x54(我知道这可能会根据屏幕想要显示单元格的方式而改变,因此大小应该不相关)这些是 Storyboard中 View 的当前显示设置 还有我的 UICollectionView 委托(delegate)代码
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
MyCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
[cell.image setImage:[UIImage imageNamed:@"avocado"]];
return cell;
}
结果看起来像这样所以你看到边缘是如何被稍微切断的。我确实阅读了一些尝试 [cell.image setContentMode:UIViewContentModeScaleAspectFit];
的其他答案,但这也没有用。有人对此有解决方案吗? UIImageView 像这样适合 UICollectionViewCell 内部
外面的蓝线是 UICollectionViewCell,里面的蓝线是 UIImageView。
最佳答案
确保在 ImageView 和单元格之间添加顶部、前导、底部和尾随约束,以便在单元格更改大小时 ImageView 的大小正确 - 否则 ImageView 将保持在 Storyboard 中看到的大小如果单元格改变大小。
您肯定还需要将 ImageView 的内容模式
(在 Storyboard图像中看到)从Scale to Fill
更改为Aspect Fit
为了使图像在不拉伸(stretch)的情况下缩放。
关于ios - UICollectionViewCell 图像中的 UIImageView 不适合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59455806/