Search code examples
swiftimageautolayoutuiimageviewnslayoutconstraint

How to make image View Height and width (Aspect Ratio) dynamic according to the image size in swift 4 or 5?


I have a collection view in which I'm populating images that I get from the backend. I'm using AutoLayout and I've statically set the imageview's height as 180 and width as screen width. But I've learnt that each image has a different height and width which I get from the backend. So, how to design my image view so that I can display the image in its original size?


Solution

  • First of all, remove the height and width constraints set on the imageView

    Next, set the leading, trailing, top, bottom constraint of the image view to 0.

    You can get the image size through the code below.

    let image = UIImage(named: "spider.jpeg")
    let imageSize = image?.size
    

    Set the size of the cell via the image size as follows

    extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
        
        ...
        
    func collectionView(_ collectionView: UICollectionView, layout    collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return yourImageSize
        }
    }