我的自定义 UICollectionViewCell 中的图像没有扩展到单元格的整个边界?

Posted

技术标签:

【中文标题】我的自定义 UICollectionViewCell 中的图像没有扩展到单元格的整个边界?【英文标题】:The image within my custom UICollectionViewCell does not extend to the entire bounds of the cell? 【发布时间】:2019-09-04 10:05:14 【问题描述】:

我正在尝试将一组图像加载到 UIViewController 内的集合视图中。我的自定义 UICollectionViewCell 中的 UIImageView 没有扩展到单元格的边界,我不明白为什么。下面是我的代码。

视图控制器:

var dragCollectionView: UICollectionView!
var dragCollectionViewWidth: CGFloat!
let borderInset: CGFloat = 3
var interCellSpacing: CGFloat = 3
var spacingBetweenRows: CGFloat = 3

let container1: UIView = 
    let v = UIView()
    v.backgroundColor = UIColor.yellow
    return v
()


override func viewDidLoad() 
    super.viewDidLoad()
    margins = view.layoutMarginsGuide
    view.backgroundColor = UIColor.white

    view.addSubview(container1)
    container1.translatesAutoresizingMaskIntoConstraints = false
    container1.heightAnchor.constraint(equalTo: margins.heightAnchor, multiplier: 0.5).isActive = true
    container1.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
    container1.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
    container1.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true

    setUpCollectionViewForPuzzlePieces()  


override func viewDidLayoutSubviews() 
    print("")
    print("viewDidLayoutSubviews ...")

    dragCollectionViewWidth = dragCollectionView.frame.width

    dragCollectionView.translatesAutoresizingMaskIntoConstraints = false
    dragCollectionView.topAnchor.constraint(equalTo: container1.topAnchor).isActive = true
    dragCollectionView.bottomAnchor.constraint(equalTo: container1.bottomAnchor).isActive = true
    dragCollectionView.leftAnchor.constraint(equalTo: container1.leftAnchor).isActive = true
    dragCollectionView.rightAnchor.constraint(equalTo: container1.rightAnchor).isActive = true

    setupLayoutDragCollectionView()


private func setUpCollectionViewForPuzzlePieces()
    let frame = CGRect.init(x: 0, y: 0, width: 100, height: 100)
    layout = UICollectionViewFlowLayout.init()
    dragCollectionView = UICollectionView.init(frame: frame, collectionViewLayout: layout)
    dragCollectionView.backgroundColor = UIColor.gray
    dragCollectionView.delegate = self
    dragCollectionView.dataSource = self

    container1.addSubview(dragCollectionView)
    dragCollectionView.translatesAutoresizingMaskIntoConstraints = false
    dragCollectionView.topAnchor.constraint(equalTo: container1.topAnchor).isActive = true
    dragCollectionView.bottomAnchor.constraint(equalTo: container1.bottomAnchor).isActive = true
    dragCollectionView.leftAnchor.constraint(equalTo: container1.leftAnchor).isActive = true
    dragCollectionView.rightAnchor.constraint(equalTo: container1.rightAnchor).isActive = true

    // Register UICollectionViewCell
    dragCollectionView.register(GirdyPickCollectionCell.self, forCellWithReuseIdentifier: cellId)


private func setupLayoutDragCollectionView()
    layout.minimumInteritemSpacing = interCellSpacing
    layout.minimumLineSpacing = spacingBetweenRows
    layout.sectionInset = UIEdgeInsets.init(top: borderInset, left: borderInset, bottom: borderInset, right: borderInset)

    guard
        let collectionViewWidth = dragCollectionViewWidth,
        let numRows = numberOfGridColumns elsereturn
    print("numRows: \(numRows)")


    let cellWidth = getCellWidth(numRows: numRows, collectionViewWidth: collectionViewWidth, interCellSpace: interCellSpacing, borderInset: borderInset)
    layout.estimatedItemSize = CGSize.init(width: cellWidth, height: cellWidth)

    print("margins.layoutFrame.width: \(margins.layoutFrame.width)")
    print("collectionViewWidth: \(collectionViewWidth)")
    print("cellWidth: \(cellWidth)")
    print("")



private func getCellWidth(numRows: CGFloat, collectionViewWidth: CGFloat, interCellSpace: CGFloat, borderInset: CGFloat) -> CGFloat

    let numSpacing = numRows - 1
    let cellWidth = (collectionViewWidth - interCellSpace * numSpacing - borderInset * 2) / numRows
    return cellWidth



extension StartGameViewController: UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
        guard let data = puzzlePieces else return 0
        return data.count
    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
        let cell = dragCollectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! GirdyPickCollectionCell
        guard let data = puzzlePieces else return cell
        cell.imageView.image = data[indexPath.row].image
        return cell
    

我的自定义 UICollectionViewCell:

class GirdyPickCollectionCell: UICollectionViewCell 

    var image: UIImage?
    var imageView: UIImageView = 
        let imgView = UIImageView()
        return imgView
    ()

    override init(frame: CGRect) 
        super.init(frame: frame)

        self.addSubview(imageView)
        self.backgroundColor = UIColor.red.withAlphaComponent(0.3)
        setUpLayout()
    

    required init?(coder aDecoder: NSCoder) 
        fatalError("init(coder:) has not been implemented")
    

    private func setUpLayout()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: frame.width).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: frame.height).isActive = true
      

控制台:

viewDidLayoutSubviews ...
numRows: 5.0
margins.layoutFrame.width: 343.0
collectionViewWidth: 100.0
cellWidth: 16.4


viewDidLayoutSubviews ...
numRows: 5.0
margins.layoutFrame.width: 343.0
collectionViewWidth: 343.0
cellWidth: 65.0

我目前得到的:

【问题讨论】:

【参考方案1】:

在您的视图控制器中实现UICollectionViewDelegateFlowLayout 并在collectionView:layout:sizeForItemAtIndexPath 中提供大小:

func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout,
                            sizeForItemAt indexPath: IndexPath) -> CGSize 
            let kWhateverHeightYouWant = 100
            return CGSize(width: collectionView.bounds.size.width, height: CGFloat(kWhateverHeightYouWant))

【讨论】:

【参考方案2】:

您可以在 imageView 的左侧(或前导)、顶部、右侧(或尾随)和底部添加约束。 如果需要,这也将帮助您设置框架之间的填充。

使用此代码:

imageView.translatesAutoresizingMaskIntoConstraints = false 
imageView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

【讨论】:

【参考方案3】:

我认为你应该设置所有边缘约束而不是给出宽度和高度, 尝试添加这样的约束

private func setUpLayout()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    imageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

【讨论】:

以上是关于我的自定义 UICollectionViewCell 中的图像没有扩展到单元格的整个边界?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的自定义 ClientHttpRequestInterceptor 响应为空

Django 1.8 没有使用我的自定义登录页面

如何在我的自定义主题中包含自定义 js 文件?

我的自定义逻辑回归实现有啥问题?

为啥我的 UISearchDisplayController 不使用我的自定义 tableViewCell?

为啥我的自定义 Swift 类没有转移到我的 GameScene [关闭]