为UIButton设置背景图像

Lin*_*nda 15 iphone xcode objective-c

我是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];
Run Code Online (Sandbox Code Playgroud)

我知道如何在Interface Builder中执行此操作,但我宁愿学习如何在XCode中执行此操作.

Lin*_*nda 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];
Run Code Online (Sandbox Code Playgroud)


Jon*_*nah 8

请参阅UIButton类参考:-setBackgroundImage:forState:

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


Lar*_*ipp 6

您需要使用以下UIButtonTypeCustom类型声明您的按钮:

btnClear = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
Run Code Online (Sandbox Code Playgroud)

然后你应该能够使用以下内容:

[btnClear setImage:[UIImage imageNamed:@"blue_button.png"] forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

可以设置6种不同的控制状态.

enum {
   UIControlStateNormal               = 0,
   UIControlStateHighlighted          = 1 << 0,
   UIControlStateDisabled             = 1 << 1,
   UIControlStateSelected             = 1 << 2,
   UIControlStateApplication          = 0x00FF0000,
   UIControlStateReserved             = 0xFF000000
};
Run Code Online (Sandbox Code Playgroud)

以下是一些可能有用的参考资料:

UIButton类参考

UIControl类参考


Nic*_*sky 3

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