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

The image within my custom UICollectionViewCell does not extend to the entire bounds of the cell?

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

ViewController:

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 else{return}
    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

我目前得到的:

您可以向 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

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

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
}

在您的视图控制器中实现 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))
}