无法在 UICollectionView 单元格和单元格子视图之间添加约束

Can't add constraints between UICollectionView cell and the cell subview

我 运行 我的应用程序崩溃了:

Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal.

我的图像是单元格的子视图。

我做错了什么?

let image = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
image.image = UIImage.init(named: "Bitmap")

cell.contentView.addSubview(image)

let bottomConstr = NSLayoutConstraint(item: image, attribute: .bottom, relatedBy: .equal, toItem: cell.contentView, attribute: .bottom, multiplier: 1, constant: 0)
//let leftConstr = NSLayoutConstraint(item: image, attribute: .leading, relatedBy: .equal, toItem: cell.contentView, attribute: .leading, multiplier: 1, constant: 0)
//let rightConstr = NSLayoutConstraint(item: image, attribute: .trailing, relatedBy: .equal, toItem: cell.contentView, attribute: .trailing, multiplier: 1, constant: 0)
let heightConstr = NSLayoutConstraint(item: image, attribute: .height, relatedBy: .equal, toItem: nil , attribute: .notAnAttribute, multiplier: 1, constant: 10)

image.addConstraint(bottomConstr)
//image.addConstraint(leftConstr)
//image.addConstraint(rightConstr)
image.addConstraint(heightConstr)

您需要在 Superview 上添加约束。所以,将它添加到单元格 contentView.

  cell.contentView.addConstraint(bottomConstr)
  cell.contentView.addConstraint(heightConstr)

缩放 UICollectionView 时,约束对我来说效果不佳。这是我调整标签大小以始终填充单元格的方法。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mycell", for: indexPath as IndexPath) as! SliceCollectionViewCell
    cell.label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}

func collectionView(_ collectionView: UICollectionView,
                             willDisplay cell: UICollectionViewCell,
                             forItemAt indexPath: IndexPath) {
    guard let cell = cell as? MyCollectionViewCell else {
        print("ERROR: wrong cell type")
        return
    }
    cell.label.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)
}