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

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

问题描述

我想在点击时更改按钮颜色。我用过:

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

任何帮助都将不胜感激。

Any help will be appreciated.

推荐答案

您可以通过编程方式创建图像,因此可以动态地使用颜色:

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

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

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

这将创建一个图像,其大小与指定颜色的按钮相同然后为希望的州分配它。由于使用了backgroundImage,您仍然可以通过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的BackgroundColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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