Iphone 在iOS 7中突出显示我的按钮

Iphone 在iOS 7中突出显示我的按钮,iphone,objective-c,ios7,uibutton,Iphone,Objective C,Ios7,Uibutton,我正在用iOS 7制作一个自定义键盘,我希望用户轻触时按钮的背景颜色会改变。但是,我不能按按钮这样做。在我分配给按钮的iAction中,我使用的代码是 if(button.highlighted==YES){ button.backgroundColor = [UIColor blackColor]; //Change background color button.titleLabel.textColor = [UIColor whiteColor]; //Change

我正在用iOS 7制作一个自定义键盘,我希望用户轻触时按钮的背景颜色会改变。但是,我不能按按钮这样做。在我分配给按钮的iAction中,我使用的代码是

    if(button.highlighted==YES){
    button.backgroundColor = [UIColor blackColor]; //Change background color
    button.titleLabel.textColor = [UIColor whiteColor]; //Change text color
    }
我做错了什么?我是否误用了“突出显示”?当我运行它时,这段代码似乎根本不会影响用户界面,我不确定用什么来替换它

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

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

    return image;
}

您可以使用此方法创建一个图像,并使用
setBackgroundImage:forState:
method

设置按钮。您也可以在
xib
中执行简单的操作。按照以下屏幕截图进行操作:-

1) 选择
按钮
,然后在
绘图
控制
部分启用
显示触摸突出显示
突出显示

更改按钮的突出显示状态:

[YourButton setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forState:UIControlStateHighlighted];
并将此方法添加到视图控制器:

- (UIImage *)imageWithColor:(UIColor *)color {
   CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
   UIGraphicsBeginImageContext(rect.size);
   CGContextRef context = UIGraphicsGetCurrentContext();

   CGContextSetFillColorWithColor(context, [color CGColor]);
   CGContextFillRect(context, rect);

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

   return image;
}

在Swift中,您可以执行以下操作:

extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
    CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
    CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    self.setBackgroundImage(colorImage, forState: forState)
}}
只要在任何类之外编写,您就可以像这样在任何地方使用它:

yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)

为此,您需要自定义按钮,这意味着必须从系统中将类型更改为自定义??不要选中突出显示,除非您希望按钮最初显示为突出显示。我建议缓存以这种方式生成的图像