![](/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.