![](/img/trans.png)
[英]how to resize the image to fit in UIImageview in a tableview cell
[英]How to fit full cell with an image
我希望单元格的背景完全充满图像,但我无法做到。
我已经尝试了所有的图像缩放,但没有一个有帮助。
代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
myCell.backgroundColor = .red
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: myCell.frame.width , height: myCell.frame.height))
let image = UIImage(named: "background")
imageView.image = image
imageView.clipsToBounds = true
myCell.backgroundView = UIView()
myCell.backgroundView!.addSubview(imageView)
return myCell
}
也许问题出在我的 imageView 的框架中? 我认为这不是因为我测试了更改 imageView 的背景颜色,并且所有单元格的红色都覆盖了蓝色。
确保您将图像添加到单元格的contentView
。
将以下内容添加到cellForItemAt
: cell.contentMode = .scaleAspectFill
这是我的UICollectionViewCell
子类。 我将UIImageView
锚定到单元格的contentView
:
struct CustomData {
var title: String
var url: String
var backgroundImage: UIImage
}
class CustomCollectionViewCell: UICollectionViewCell {
var data: CustomData? {
didSet {
guard let data = data else { return }
imageView.image = data.backgroundImage
}
}
fileprivate let imageView: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
iv.layer.cornerRadius = 12
return iv
}()
override init(frame: CGRect) {
super.init(frame: .zero)
contentView.addSubview(imageView)
imageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.