调整与自动布局中的CollectionView在CollectionViewCell自动图像(Res

2019-10-23 04:51发布

我有水平UICollectionViewFlowLayout一个的CollectionView。

我想实现:

如果设备取向为纵向,宽度的UIImageView将QUAL到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
}

Answer 1:

如果你使用正确UIImageView调整大小设置(比如,适应方面/填充),那么你只需要在单元格的高度设置为你的CollectionView的(你获得一个指向它的一个...sizeForItemAtIndexPath...方法参数)高度。 你也应该叫- layoutIfNeeded事后你的细胞的方法。



Answer 2:

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



文章来源: Resize images automatically in CollectionViewCell in CollectionView with Auto Layout