Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...