Tyler
Tyler

Reputation: 2386

Changing background image of uibutton makes frame huge

I am programmatically changing the background of a uibutton with this code:

firstButton.setImage(UIImage(named: "drinks-sub-first"), forState: UIControlState.Normal)

trouble is the button is no longer constrained by the constraints I set up in the .xib file and takes up the entire screen now. What am I doing wrong? How can I make the button stay the same size as it was before changing the background image?

also I tried this approach already

var frame = firstButton.frame
firstButton.setImage(UIImage(named: "drinks-sub-first"), forState: UIControlState.Normal) //tried setBackgroundImage function as well
firstButton.frame = frame

Upvotes: 0

Views: 976

Answers (3)

cbiggin
cbiggin

Reputation: 2142

Check on the constraints that you've set for the button. You should have the width and height set to "less than or equal" to whatever value you want; you might have them set to "greater than or equal". Or if you want them the same width and height no matter what, then set the constraints to "equal" the value.

Upvotes: 1

Mike Sabatini
Mike Sabatini

Reputation: 2551

You are not setting the background image with the method setImage(). That method sets the accessory image on a UIButton.

To set the background image for a button use the method:

setBackgroundImage(image: UIImage?, forState state: UIControlState)

Upvotes: 1

user3147770
user3147770

Reputation: 203

I'm a newb, but I've gotten so much help here I feel compelled to help anytime I get an inkling I can. Check out this quick tutorial on working with button background images: http://www.raywenderlich.com/78264/learn-to-code-ios-apps-with-swift-tutorial-5

From the tutorial:

You may notice your button looks a little bit squished at this point. This is because you have hardcoded width and height constraints that are smaller than the image itself. (in your case, it's the opposite I guess, but still ...)

Luckily, there is an easy way to fix this. All views have something called an intrinsic content size, which you can think of as an automatic constraint that is set to the size of the element being presented. In the case of an image, it will be the size of the image itself.

So rather than having hardcoded width and height constraints, you can rely on the intrinsic content size of the image to size the image view appropriately.

Upvotes: 0

Related Questions