问题描述
我希望单元格的背景完全充满图像,但是我无法做到。
我已经尝试了所有的图像缩放比例,但是都没有帮助。
代码:
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的背景色,并且所有单元格的红色都覆盖了蓝色。
解决方法
您将不得不在此处使用约束,因此将此extension添加到项目中的文件中。
然后代替
myCell.backgroundView!.addSubview(imageView)
执行此操作
myCell.backgroundView!.embedView(imageView)
您可能想了解有关自动版式n约束的更多信息,所以here是文档
,确保将图像添加到单元格的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")
}
}