Adrian Adrian - 1 month ago 14
iOS Question

UIButton's backgroundImage's content mode not respected

I'm putting the finishing touches on an app I'm about to publish and I've enountered difficulty getting the

contentMode
of a
UIButton
's background image to be respected. Regardless of the
contentMode
I specify, the image just gets plopped in the background with no regard for the
contentMode
setting.

I've looked at a post covering this topic, but it doesn't appear to do anything in my circumstance.

This is called in from
viewDidLoad
:

// I tried putting the contentMode lines here...
myButton.imageView!.contentMode = .scaleAspectFit
myButton.contentMode = .scaleAspectFit
myButton.setBackgroundImage(UIImage(named: "myImage.png"), for: .normal)

// ...and here
// myButton.imageView!.contentMode = .scaleAspectFit
// myButton.contentMode = .scaleAspectFit

// I threw this in for S's & G's to see if it would work...it didn't
myButton.translatesAutoresizingMaskIntoConstraints = false
myButton.imageView?.translatesAutoresizingMaskIntoConstraints = true


I'm not sure what I'm missing, but I rest assured it will be something startling stupid on my part. I welcome suggestions on how I can get the
contentMode
of a
UIButton
's background image to be respected. Thank you for reading.

Update

The button is typed as a custom button, not a system button.

Answer

The problem is that you add an image using setBackgroundImage() method. This adds your image to some background image view and you can't reach this view from your button like myButton.imageView!. So in your code you set contentType for another empty UIImageView.

If you want to reach this background UIImageView you can use .subviews array, but if you try to do it inside your viewDidLoad() method, you'll find that this ImageView is not there yet. It'll be added later, before your button will be shown. So try to do it this way using viewDidAppear() method.

Hope that this'll help. Sorry for my English.

override func viewDidLoad() {
    myButton.setBackgroundImage(UIImage(named: "myImage"), for: .normal)
    myButton.setTitle("Some title", for: .normal)
}

override func viewDidAppear(_ animated: Bool) {
    (myButton.subviews[0] as! UIImageView).contentMode = .scaleAspectFit
}
Comments