簡體   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