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

Resize images automatically in CollectionViewCell in CollectionView with Auto Layout

我有一个带有水平 UICollectionViewFlowLayout 的 collectionView。

我正在努力实现:

如果设备方向是纵向,UIImageView 宽度将等于 view.width 并自动计算高度(就像自动布局通常发生的那样)。横向模式也一样。 示例 - Iphone.

上的标准照片应用

不幸的是,我不知道如何使用 autoLayout 实现它。我对 UIImageView 设置了约束,使其大小与单元格相等。但看起来销售本身无法固定到父视图。

阅读类似问题后,看起来必须使用

以编程方式调整单元格大小
func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {



return CGSize(width: width, height: height)

}

我卡在这里了,因为我知道屏幕的宽度,但不知道如何动态计算高度。

关于图片高度:

我的图片声明如下:

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
}

您可以使用 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)

如果您使用正确的 UIImageView 调整大小设置(例如,纵横比 fit/fill),那么您只需将单元格的高度设置为您的 collectionView 的高度(您会得到一个指向它的指针作为其中之一...sizeForItemAtIndexPath... 方法参数)高度。之后您还应该在您的单元格上调用 - layoutIfNeeded 方法。