Store Search Exercise pg 199

I could not figure out how to resize the images in the buttons. I used the code from the resizedImage function from MyLocations, but I just can’t figure out why it is not working.

I added this extension:

extension UIImage {
  func resizedImage(withBounds bounds: CGSize) -> UIImage {
    let horizontalRatio = bounds.width / size.width
    let verticalRatio = bounds.height / size.height
    let ratio = min(horizontalRatio, verticalRatio)
    let newSize = CGSize(width: size.width * ratio,
                         height: size.height * ratio)
    
    UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
    draw(in: CGRect(origin: CGPoint.zero, size: newSize))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return newImage!
  }
}

Then I added these properties to the button.imageView

  button.imageView?.clipsToBounds = true
  button.imageView?.contentMode = .scaleAspectFill
  let resizedImage = image.resizedImage(withBounds: CGSize(width: 60.0, height: 60.0))

  button.setImage(resizedImage, for: .normal)

But it is not seeming to do anything to the non-square images

I solved this at least one way.

I needed to add the code to scale the image where I create the button (loop in tileButtons). Not where I downloaded the image (downloadImage). Additionally, I needed a couple other parameters set on the content. Here is what I added to have it work:

  button.imageView?.clipsToBounds = true
  button.contentHorizontalAlignment = .fill
  button.contentVerticalAlignment = .fill
  button.imageView?.contentMode = .scaleAspectFill

This fills the entire button with the image. I still wanted a little padding, so I used:

  button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

This gave a little space between the image and the button.