为UIButton设置背景图片

16

我是Objective C的新手。如何将此按钮的背景设置为图像(图像已经在XCode的资源文件夹中,名称为“blue_button.png”),而不是透明的?另外,我希望使用该图像作为按钮的形状,而不是使用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中实现。


如果您使用nib,可以在Interface Builder中完成此操作。 - Vjy
你应该接受一个答案,这对所有人都有好处... - whyoz
7个回答

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

8

请参考UIButton类参考文档-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 类引用

UIControl 类引用

这些资料可能会对您有所帮助。

这个是有效的,但我现在不确定如何设置标题。我之前使用的是<code>[btnClear setTitle:@"Clear" forState:UIControlStateNormal];</code>。 - Linda
看看这个,看看它是否有帮助。https://dev59.com/uHM_5IYBdhLWcg3wPAZF - Larry Hipp
你可以设置一个图像或标题,但有一些事情可以做,以使标题显示。 - Larry Hipp

3

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


2

Swift 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)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接