Automatically resizes images in a CollectionViewCell in an auto-composited CollectionView

I have a collectionView with a horizontal UICollectionViewFlowLayout.

Here is the layout:

I am trying to achieve:

If the device orientation is portrait, the UIImageView will be wide enough for viewing. width and allow the height to be calculated automatically (as is usually the case with automatic layout). And the same for landscape mode. An example is a standard Iphone photography app.

Unfortunately I can't see how to do this with autoLayout. I have set constraints on the UIImageView to be equal in size to the cell. But it looks like the sale itself cannot be tied to the Parent View.

After reading similar questions, it looks like the cells should be programmatically changed with

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



return CGSize(width: width, height: height)

}

      

And so I'm stuck because I know the width of the screen, but I don't know how to dynamically calculate the height.

About Image Height:

I have my image declared like this:

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
}

      

+2


source to share


2 answers


If you are using the correct sizing UIImageView

(like fit / fill), you just need to set the cell height in your CollectionView (you get a pointer to it as one of the method parameters ...sizeForItemAtIndexPath...

) the height. After that, you must also call the method - layoutIfNeeded

on your cell.



+4


source


You can use sizeForItemAtIndexPath:

to resize collection view cell.

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)
}

      

You can get the cell size via:

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

      



You can get the size of the image with:

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

      

If you want to change the height, change it manually to return CGSize(width: collectionCellWidth , height: cellheight)

+2


source







All Articles