iPhone:如何使用 buttonType UIButtonTypeCustom 设置 UIButton 的背景颜色 [英] iPhone : How to set BackgroundColor of UIButton with buttonType UIButtonTypeCustom

查看:20
本文介绍了iPhone:如何使用 buttonType UIButtonTypeCustom 设置 UIButton 的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单击时更改按钮颜色.我用过:

i want to change the button color when it is clicked. I used :

[button setBackgroundColor:[UIColor redColor]];

但这仅在按钮的四个角上而不是在整个按钮上显示红色,而且当我使用 forState:UIControlStateNormal 然后应用程序挂起.他们有什么方法可以在单击时在按钮上显示某种颜色?

but this shows red color only on the four corners of button not on the whole button and also when i use forState:UIControlStateNormal then the application hangs. Is their any way to show some color on button when clicked?

[click1 setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];

任何帮助将不胜感激.

推荐答案

您可以通过编程方式创建图像,从而能够以动态方式使用您的颜色:

You could create an image programmatically and so have the ability to use your colors in a dynamic way:

使用此方法为 UIButton 创建一个类别,并确保通过 @import QuartzCore 导入 QuartzCore 库:

Create a category for UIButton with this method and be sure to have QuartzCore lib imported via @import QuartzCore:

- (void)setColor:(UIColor *)color forState:(UIControlState)state
{
    UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    colorView.backgroundColor = color;

    UIGraphicsBeginImageContext(colorView.bounds.size);
    [colorView.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:colorImage forState:state];
}

这将为您的指定颜色创建一个具有按钮大小的图像,然后将其分配给所需的状态.由于背景图像的使用,您仍然可以通过 setTitle:forState: 方法为按钮设置标题.

This is gonna create an image with the size of your button for your specified color and then assigning it for the wished state. Because of the usage of the backgroundImage you can still set a title for the button via the setTitle:forState: method.

这篇关于iPhone:如何使用 buttonType UIButtonTypeCustom 设置 UIButton 的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆