如何使整个单元格适合图像

问题描述

我希望单元格的背景完全充满图像,但是我无法做到。
我已经尝试了所有的图像缩放比例,但是都没有帮助。
代码:

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
}

这是它的样子:

enter image description here

问题可能出在我的imageView框架上吗?我认为不是因为我测试了更改imageView的背景色,并且所有单元格的红色都覆盖了蓝色。

解决方法

您将不得不在此处使用约束,因此将此extension添加到项目中的文件中。

然后代替

myCell.backgroundView!.addSubview(imageView)

执行此操作

myCell.backgroundView!.embedView(imageView)

您可能想了解有关自动版式n约束的更多信息,所以here是文档

,

确保将图像添加到单元格的contentView

将以下内容添加到cellForItemAtcell.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")
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...