When displaying an image from a URL to UIImageView, you may be at a loss for a moment. In these cases, it's easier to use an image loading library such as Nuke or Kingfisher.
Nuke.loadImage(with: url, into: imageView)
Nuke is convenient to use by itself, but it is necessary to think a little about how to deal with the possibility that the ratio will differ depending on the image to be loaded. In this article, I'll show you how to calculate the ratio and make it perfect via AutoLayout in such cases.
Nuke.loadImage(with: URL(string: imageURL)!, options: ImageLoadingOptions(), into: self.writingImageView, progress: nil) { (result: Result<ImageResponse, ImagePipeline.Error>) in
switch result {
case .success(let imageResponse):
self.imageRateLayoutConstraint.constant = imageResponse.image.size.width / imageResponse.image.size.height
case .failure(let error):
print(error)
}
}
}
You can use Nuke's completion option to get the size of the acquired image in this way and calculate the ratio, so you can change AutoLayout from the code by substituting it into ʻimageRateLayoutConstraint.constant`.
To add an Auto Layout setting for your image, set the Aspect Ratio like this:
Then define @IBOutlet weak var imageRateLayoutConstraint: NSLayoutConstraint!
And connect on the Storyboard.
Recommended Posts