如何让UIImageView填满UICollectionViewCell且图片不拉伸不裁剪适配所有机型
实现UIImageView上下填充满UICollectionViewCell且不拉伸不裁剪的方案
要实现该需求,核心逻辑是动态根据每张图片的原始宽高比计算对应CollectionViewCell的宽度,保证cell的高度固定为你需要的上下填充高度,宽度随图片比例自适应,搭配UIImageView的scaleAspectFit内容模式即可实现既不拉伸、也不裁剪的效果。
原效果参考
- Aspect Fit效果

- Aspect Fill效果

代码修改步骤
1. 配置UICollectionViewCell约束
保证UIImageView完全撑满整个cell的contentView,内容模式保持Aspect Fit:
import UIKit class DataCollectionViewCell: UICollectionViewCell { @IBOutlet weak var img: UIImageView! override func awakeFromNib() { super.awakeFromNib() img.contentMode = .scaleAspectFit // 若使用xib/Storyboard可直接在可视化界面配置以下约束,无需代码书写 img.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ img.topAnchor.constraint(equalTo: contentView.topAnchor), img.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), img.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), img.trailingAnchor.constraint(equalTo: contentView.trailingAnchor) ]) } }
2. 实现动态Cell尺寸计算
在UICollectionViewDelegateFlowLayout的代理方法中,根据图片宽高比计算每个cell的宽度:
extension ViewController : UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imgArr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DataCollectionViewCell cell.img.image = UIImage(named:imgArr[indexPath.row]) return cell } // 动态计算Cell尺寸 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // 取CollectionView的高度作为Cell的固定高度,实现上下填充满 let cellHeight = collectionView.bounds.height guard let image = UIImage(named: imgArr[indexPath.row]) else { // 兜底默认尺寸 return CGSize(width: cellHeight, height: cellHeight) } // 根据图片宽高比计算Cell宽度 let cellWidth = image.size.width / image.size.height * cellHeight return CGSize(width: cellWidth, height: cellHeight) } // 可自定义的间距配置 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 // 水平方向Cell之间的间距 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) // 整个Section的左右边距 } }
适配说明
该方案会自动适配所有机型,Cell高度会跟随当前CollectionView的高度动态调整,宽度始终匹配图片原始比例,不会出现拉伸、裁剪问题。
内容的提问来源于stack exchange,提问作者user1163234
相关产品推荐
相关产品推荐

