Let's say one has a placeholder image, which is loaded into an UIImageView. Then, an async operation eventually loads an image with a different size.
The issue I am observing is that I don't know how to make imageView to "wrap" the new image, according to its size, preserving the image original aspect ratio.
Note that when using contentMode=.scaleAspect*, the view scales the image to fit its view. In my case, I want the view to fit the image.
import Foundation
import UIKit
class ViewController: UIViewController {
let imageView = UIImageView()
override func loadView() {
let view = UIView()
view.addSubview(imageView)
imageView.contentMode = .scaleAspectFill
imageView.backgroundColor = .red
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
imageView.widthAnchor.constraint(equalToConstant: 100),
imageView.heightAnchor.constraint(equalToConstant: 100),
])
self.view = view
}
override func viewDidLoad() {
// imageView.image = // some placeholder image is shown; size is 100 x 100
// imageView.image = // network call is made which eventually loads a different image with dynamic size
}
}
// Present the view controller in the Live View window
import PlaygroundSupport
PlaygroundPage.current.liveView = ViewController()