0
votes

I'm displaying an image on top of a button, everything is OK on iPhone 7 e.g. :

enter image description here

I set button background color to blue to see the button frame.

Since I set an aspect ratio on my button's parent view, the button size change on small device, and on iPhone 4S, I have :

enter image description here

The button's images are not resized. This is my code :

public extension UIButton {

    func setButtonWithTextBehindImage () {
        let spacing = CGFloat(0.0)

        let imageSize = self.imageView?.frame.size
        self.titleEdgeInsets = UIEdgeInsetsMake(0.0, -(imageSize?.width)!, -((imageSize?.height)! + spacing), 0.0)
        let titleSize = self.titleLabel?.frame.size
        self.imageEdgeInsets = UIEdgeInsetsMake(-((titleSize?.height)!), 0.0, 0.0, -(titleSize?.width)!)
    }
}

I tried to set contentMode .scaleAspectFit on button and on button imageView but everytime my imageSize is (30, 30) (the size of my @1x image) and it doesn't resize to button size.

How can I do ? TY

1

1 Answers

0
votes

Could you provide a bit more context on how you're using the code snippet you provided (maybe some code that we could try running)? Documentation from https://developer.apple.com/reference/uikit/uibutton/1624010-titleedgeinsets mention insets being applied after the rectangle has been sized to fit. The time at which you're calling your function in the extension might have an effect on the expected resize not happening - as in, are you calling this when the view is loaded, after it appears, after subviews have been laid out.