Joshua
Joshua

Reputation: 15500

Creating a Custom UIButton

I am looking to create a Custom UIButton (not subclass) progrmatically, I would like it to have a background image that will stretch as the UIButton's width increases. How would I do this?

Upvotes: 3

Views: 10688

Answers (4)

Klaus Busse
Klaus Busse

Reputation: 159

Well, UIView's contentStretch property would be the correct solution, but unfortunately it doesn't work with the UIButton background property (XCode 4.0.2 at least). It is even exposed in IB, so you wouldn't need any code for it.

Upvotes: 0

Rolf Hendriks
Rolf Hendriks

Reputation: 271

Better yet, use UIView's contentStretch property. Otherwise, you might get some nasty surprises if you use stretchableImageWithLeftCapWidth to shrink a graphic or to stretch a complex graphic with lighting or gloss effects.

Upvotes: 1

Nick Forge
Nick Forge

Reputation: 21464

First create a stretchable UIImage (this assumes the 'cap' at the end of your button image is 10px):

UIImage *backgroundImage = [[UIImage imageNamed:@"ImageBackground.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];

Then use the stretchable image as the background:

[myButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];

When you set the backgroundImage on a UIButton for UIControlStateNormal, it acts as the background for all states, unless you explicitly set a different backgroundImage for any of the other states.

Upvotes: 15

Thomas Kekeisen
Thomas Kekeisen

Reputation: 4406

You have to set an UIImage created with the "stretchableImageWithLeftCapWidth:topCapHeight:"-Method as button background. For example:

UIImage *yourBackgroundImage = [[UIImage imageNamed:@"yourImage.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
yourButton.backgroundColor = [UIColor colorWithPatternImage:yourBackgroundImage];

Upvotes: -4

Related Questions