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

时间:2016-11-10 12:09:24

标签: ios swift uicollectionview uicollectionviewcell

运行我的应用后,它崩溃了:

  

无法在视图上安装约束。约束是否引用了视图子树之外的内容?这是非法的。

我的图片是细胞的子视图。

我做错了什么?

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)

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

在缩放 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)
}