繁体   English   中英

如何用图像适应整个单元格

[英]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 的背景颜色,并且所有单元格的红色都覆盖了蓝色。

您必须在此处使用约束,因此将此扩展名添加到项目中的文件中。

然后代替

myCell.backgroundView!.addSubview(imageView)

做这个

myCell.backgroundView!.embedView(imageView)

您可能想阅读有关 Autolayout n Constraints 的更多信息,因此这里是文档

确保您将图像添加到单元格的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")
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM