2011-01-05 180 views
15

我是一个Objective C的新手。我如何将这个按钮的背景设置为一个图像(图像已经在XCode的资源文件夹中,“blue_button.png”)而不是clearColor?此外,我宁愿我使用图像作为按钮的形状,而不是UIButtonTypeRoundedRect。为UIButton设置一个背景图像

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

我知道如何在Interface Builder中做到这一点,但我宁愿了解如何在XCode中做到这一点。

+0

你可以做,在Interface Builder如果你使用笔尖 – Vjy 2011-01-05 19:42:51

+0

你应该接受一个答案,这是对所有参与者都有好处...... – whyoz 2016-07-11 10:21:16

回答

2

您可以使用[UIColor colorWithPatternImage:]设置图像的背景颜色。要使用图像,您应该将按钮样式更改为自定义。

8

UIButton class reference-setBackgroundImage:forState:

创建UIButtonTypeCustom类型,而不是你的UIButtonTypeRoundedRect按钮,如果你不想使用圆角风格。

6

您需要具有以下UIButtonTypeCustom类型来声明按钮:

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

那么你应该可以使用如下:

[btnClear setImage:[UIImage imageNamed:@"blue_button.png"] forState:UIControlStateNormal]; 

有可以设定6个不同的控制状态。

enum { 
    UIControlStateNormal    = 0, 
    UIControlStateHighlighted   = 1 << 0, 
    UIControlStateDisabled    = 1 << 1, 
    UIControlStateSelected    = 1 << 2, 
    UIControlStateApplication   = 0x00FF0000, 
    UIControlStateReserved    = 0xFF000000 
}; 

这里有一些参考资料,可以帮助:

UIButton Class Reference

UIControl Class Reference

+0

这确实有效,但我现在不确定如何设置标题。我正在使用[btnClear setTitle:@"Clear" forState:UIControlStateNormal]; Linda 2011-01-05 21:16:06

+0

看看这个,看看是否有帮助。 http://stackoverflow.com/questions/1469474/setting-an-image-for-a-uibutton-in-code – 2011-01-05 21:45:17

+0

你可以设置和图像或瓷砖,但有一些事情,你可以做的,以获得标题显示 – 2011-01-05 21:45:51

42

这工作:

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

请将此答案标记为已接受... – 2013-11-10 06:30:42

1

无需设置按钮UIButtonTypeCustom- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state方法也适用为UIButtonTypeRoundedRect如果要设置按钮的背景与互联网上的图像

1

,使用SDWebImage是一个优雅的选择:

#import <SDWebImage/UIButton+WebCache.h> 

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)]; 
[button setBackgroundImageWithURL:imageURL forState:UIControlStateNormal];