为UIButton设置背景图像

时间:2011-01-05 19:40:54

标签: iphone objective-c xcode

我是Objective C的新手。如何将此按钮的背景设置为图像(图像已经在XCode的资源文件夹中,“blue_button.png”)而不是clearColor?另外,我更喜欢使用图像作为按钮的形状而不是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];

我知道如何在Interface Builder中执行此操作,但我宁愿了解如何在XCode中执行此操作。

7 个答案:

答案 0 :(得分:44)

这有效:

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

答案 1 :(得分:8)

请参阅UIButton class reference-setBackgroundImage:forState:

如果您不想使用圆角样式,请创建类型为UIButtonTypeCustom而不是UIButtonTypeRoundedRect的按钮。

答案 2 :(得分: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

答案 3 :(得分:3)

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

答案 4 :(得分:1)

无需设置按钮UIButtonTypeCustom - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state方法也适用于UIButtonTypeRoundedRect

答案 5 :(得分:1)

如果您想在互联网上设置图像的按钮背景,使用SDWebImage是一个优雅的选择:

#import <SDWebImage/UIButton+WebCache.h>

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

答案 6 :(得分:0)

快速4 +

var btnClear = UIButton()
btnClear = UIButton(type: .custom)
btnClear.frame = CGRect(x: 115, y: 200, width: 90, height: 40)
btnClear.setBackgroundImage(UIImage(named: "blue_button.png"), for: .normal)
view.addSubview(btnClear)