How can I create a big, red UIButton with iOS?

Using iOS, how would I go about creating a red "delete" button similar to the one used when deleting contacts on the iPhone?


You first start with a stretchable image:

alt text http://grab.by/4lP

Then you make a button with the stretched image as the background and apply text.

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 52)];
[sampleButton setTitle:@"Button Title" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];
[sampleButton setBackgroundImage:[[UIImage imageNamed:@"redButton.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton];

Obviously, you will need to adjust the frame origin and size to match your app, as well as the target, selector, and title.


I've also made some buttons...retina and non-retina versions

If you want to use them in a Cell just use the following code in cellForRowAtIndexPath:

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:[cell.contentView frame]];
[sampleButton setFrame:CGRectMake(0, 0, cell.bounds.size.width-20, 44)];
[sampleButton setBackgroundImage:[UIImage imageNamed:@"button_red.png"] forState:UIControlStateNormal];
[cell addSubview:sampleButton];

Green Button Normal

Red Button Normal

Grey Button Normal

Green Button RetinaRed Button RetinaGrey Button Retina


I think those ones are better (and they look fine on retina display too) :

alt textalt text

.png generated from this very nice .psd file : http://www.teehanlax.com/blog/2010/08/12/iphone-4-gui-psd-retina-display/

And then use it as a strechable image for the background of your UIButton:

UIImage* greenButton = [UIImage imageNamed:@"UIButton_green.png"]; 
UIImage *newImage = [greenButton stretchableImageWithLeftCapWidth:greenButton.size.width/2 topCapHeight:greenButton.size.height/2];
[callButton setBackgroundImage:newImage forState:UIControlStateNormal];