Creating a Custom UIButton

10,649

Solution 1

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.

Solution 2

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.

Share:
10,649
Joshua
Author by

Joshua

Objective-C and Swift programmer with almost 10 years experience. Began developing on Mac and now focussing on iOS. Current app focus is in the area of development tools and rich text editing. Interested in compiler and interpreter design. Dabbles with PHP, HTML/CSS, Javascript and Python. Fan of Star Trek & Twin Peaks.

Updated on June 04, 2022

Comments

  • Joshua
    Joshua almost 2 years

    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?