Display images with exact AutoLayout ratio using image loading library Nuke in Swift

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:

CleanShot 2020-10-08 at 18.38.37@2x.png

Then define @IBOutlet weak var imageRateLayoutConstraint: NSLayoutConstraint! And connect on the Storyboard.

Recommended Posts

Display images with exact AutoLayout ratio using image loading library Nuke in Swift
Display around fonts in Japanese with Swift: macOS
Use C library with Swift using Clang Modules (modulemap)
Display a loading image in JavaFX and then display another image
Succeeded in loading js manually compiled using webpack with rails6