ImageView 的约束不起作用

Constrains for ImageView is not working

我已将 AutoLayout 与我的其中一个 UICollectionView 一起使用 我遇到了 imageView 的高度和宽度问题。我在我的 UICollectionViewCell 中添加了 UIImageView,如下面的约束。

UICollectionViewDataSource 方法。

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    var width = Int((collectionView.frame.size.width - 30) / 4)
    if width % 2 != 0 {
        width += 1
    }        
    return CGSize(width: CGFloat(width), height: CGFloat(width))
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
    print("Cell Size - \(cell.bounds)")
    print("ImageView Size - \(cell.imageView.frame)")
    return cell
}

但是当我 运行 这个 ImageView 总是与 70X70 一起出现时,无论我将在哪个设备上 运行 但是 UICollectionViewCell 大小正在增加并在不同的设备上减少。

在 iPhone 6 上它看起来像下面。

我已将 UIImageViewbackgroundColor 设置为白色,UICollectionViewCell 设置为红色,这样可以更好地理解 Cell 和 ImageView 大小的控制台日志,如下所示。

Cell Size - (0.0, 0.0, 86.0, 86.0)
ImageView Size - (5.0, 5.0, 70.0, 70.0)
Cell Size - (0.0, 0.0, 86.0, 86.0)
ImageView Size - (5.0, 5.0, 70.0, 70.0)

请任何人帮助我,为什么 imageView 大小没有根据 UICollectionViewCell 增加或减少。任何帮助将不胜感激。

您需要设置约束,如下图所示;

经过一番研究后,我想出了以下方法来解决这个 AutoLayoutUICollectionViewCell 的问题。从 Xcode 6 CollectionViewCell 没有在界面生成器中显示 contentView,所以在单元格的 awakeFromNib 中我设置了它的 autoresizingMask 并且它像魅力一样工作.

class CustomCell: UICollectionViewCell {
  @IBOutlet
  var imageView: UIImageView!

    override func awakeFromNib() {
      super.awakeFromNib()
      //Below line solved my problem
      self.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    }
}

水平居中和垂直居中当将所有边固定到父级时,不应存在约束(顶部、底部、前导和尾随)已为您的图像视图提供。

或者移除水平居中和垂直居中约束 或 Top,Bottom,Leading & Trailing 并给出 与父级相同的宽度和高度以及垂直和水平中心 y.

似乎删除水平居中和垂直居中约束肯定会解决您的问题,试一试。

希望对您有所帮助。 祝你好运。

在集合视图的大小检查器中,将估计大小设置为None