1

How can I add UIViewContentMode.center to this UIImageView while also keeping .scaleAspectFill?

func insertImage() {
    let theImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 300))
    theImageView.image = #imageLiteral(resourceName: "coolimage")
    theImageView.contentMode = UIViewContentMode.scaleAspectFill
    view.addSubview(theImageView)
}

Furthermore, can somebody explain to me what the "view" exactly is in the last line "view.addSubview(theImageView)"? Is it the mysterious "view hierarchy" that I read about? Why can't I simply initialize the UIImageView? Why must it be bound to something called "view" that I haven't explicitly created? There is only a UIViewController and a UIImageView so far.

youareawaitress
  • 387
  • 2
  • 17

1 Answers1

0

As far as I know, you can't set content mode to both aspect fit and center. However, center will do what aspect fit does providing the image size is smaller than the size of the imageView. If not, use aspect fit. The following code ought to allow you to differentiate between the two:

if (theImageView.bounds.size.width > UIImage(named: "coolimage")?.size.width && theImageView.bounds.size.height > UIImage(named: "coolimage")?.size.height) {
   theImageView.contentMode = .aspectFit
} else {
   theImageView.contentMode = .center
}

As for the second part of your question, I'll refer you to this thread, which has a fairly comprehensive explanation of UIViewController vs UIView. Hope that helps.

Tom
  • 513
  • 2
  • 5
  • 20