Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a background image for UIButton

I am a newbie with Objective C. How would I set the background of this button to an image (image is already in the resources folder in XCode, "blue_button.png") instead of clearColor? Also, I would prefer that I use the image as the shape of the button rather than the UIButtonTypeRoundedRect.

btnClear = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];

btnClear.frame = CGRectMake(115, 350, 90, 40);

[btnClear setTitle:@"Clear" forState:UIControlStateNormal];

btnClear.backgroundColor = [UIColor clearColor];

[btnClear addTarget:self action:@selector(clearAction:) 

forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btnClear];

I know how to do this in Interface Builder but I would rather learn about doing it in XCode.

like image 562
Linda Avatar asked Jan 05 '11 19:01

Linda


2 Answers

This works:

UIButton *btnClear = [[UIButton alloc] init];
btnClear = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
btnClear.frame = CGRectMake(115, 200, 90, 40);
[btnClear setTitle:@"Clear" forState:UIControlStateNormal];
[btnClear setBackgroundImage:[UIImage imageNamed:@"blue_button.png"] forState:UIControlStateNormal];
[btnClear addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnClear];
like image 170
Linda Avatar answered Oct 06 '22 00:10

Linda


See the UIButton class reference: -setBackgroundImage:forState:

Create your button with type UIButtonTypeCustom instead of UIButtonTypeRoundedRect if you don't want to use the rounded corner style.

like image 40
Jonah Avatar answered Oct 05 '22 23:10

Jonah