使用自动布局在CollectionView的CollectionViewCell中自动调整图像大小

我有一个水平的UICollectionViewFlowLayout的collectionView。

这是布局:

我正在努力实现:

如果设备方向是纵向,则UIImageView宽度将被视为宽度,并自动计算高度(就像通常在自动布局中发生的那样)。 和风景模式一样。 示例 – iPhone上的标准照片应用程序。

不幸的是,我不明白如何用autoLayout实现它。 我为UIImageView设置了与单元大小相同的约束。 但看起来像卖本身不能被固定到父视图。

看完类似的问题看起来像单元格必须通过编程resize

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

而在这里我卡住,因为我知道屏幕的宽度,但不知道如何dynamic计算高度。

关于图像高度:

我有这样的声明:

 var pageImages = [UIImage]() override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell: ImageDetailViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ImageDetailViewCell let curr = indexPath.row let imgName = data[albumNumber][curr]["image"] cell.DetailImageView.image = UIImage(named: imgName!) return cell } 

如果你使用适当的UIImageViewresize设置(比如方面适合/填充),那么你只需要设置单元格的高度为你的collectionView的(你得到一个指针...sizeForItemAtIndexPath...方法参数之一)高度。 之后,您还应该在您的单元格上调用- layoutIfNeeded方法。

您可以使用sizeForItemAtIndexPath:更改集合视图单元格的大小。

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var numberOfCellInRow : Int = 3 var padding : Int = 5 var collectionCellWidth : CGFloat = (self.view.frame.size.width/CGFloat(numberOfCellInRow)) - CGFloat(padding) return CGSize(width: collectionCellWidth , height: collectionCellWidth) } 

您可以通过以下方式获取单元格的大小:

 ((UICollectionViewFlowLayout) self.collectionViewName).itemSize.height) 

您可以通过以下方式获取图像大小:

 let sizeOfImage = image.size let height = image.height 

如果你想改变高度,然后通过return CGSize(width: collectionCellWidth , height: cellheight)