是否可以改变UIButtons的背景颜色?

时间:2022-07-09 00:39:46

This one has me stumped.

这个让我为难。

Is it possible at all to change the background color of a UIButton in Cocoa for iPhone. I've tried setting the background color but it only changes the corners. setBackgroundColor: seems to be the only method available for such things.

是否有可能改变用户界面按钮的背景颜色在可可为iPhone。我试过设置背景颜色,但它只改变了角落。setBackgroundColor:似乎是这种东西唯一可用的方法。

[random setBackgroundColor:[UIColor blueColor]];
[random.titleLabel setBackgroundColor:[UIColor blueColor]];

16 个解决方案

#1


155  

This can be done programmatically by making a replica:

可以通过编程方式创建副本:

    loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    loginButton.backgroundColor = [UIColor whiteColor];
    loginButton.layer.borderColor = [UIColor blackColor].CGColor;
    loginButton.layer.borderWidth = 0.5f;
    loginButton.layer.cornerRadius = 10.0f;

edit: ofcourse, you'd have to #import <QuartzCore/QuartzCore.h>

编辑:当然,你需要#import

edit: to all new readers, you should also consider a few options added as "another possibility". for you consideration.

编辑:对于所有的新读者,你也应该考虑添加一些选项作为“另一种可能性”。为你考虑。

As this is an old answer, I strongly recommend reading comments for troubleshooting

由于这是一个旧的答案,我强烈推荐阅读评论来排除故障。

#2


59  

I have a different approach,

我有不同的方法,

[btFind setTitle:NSLocalizedString(@"Find", @"") forState:UIControlStateNormal];    
[btFind setBackgroundImage:[CommonUIUtility imageFromColor:[UIColor cyanColor]] 
        forState:UIControlStateNormal];
btFind.layer.cornerRadius = 8.0;
btFind.layer.masksToBounds = YES;
btFind.layer.borderColor = [UIColor lightGrayColor].CGColor;
btFind.layer.borderWidth = 1;

From CommonUIUtility,

从CommonUIUtility,

+ (UIImage *) imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    //  [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ;
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Don't forget to #import <QuartzCore/QuartzCore.h>

不要忘记#import

#3


32  

I assume you're talking about a UIButton with UIButtonTypeRoundedRect? You can't change the background color of that. When you try changing it's background color you're rather changing the color of the rect the button is drawn on (which is usually clear). So there are two ways to go. Either you subclass UIButton and overwrite its -drawRect: method or you create images for the different button states (which is perfectly fine to do).

我想你说的是带有UIButtonTypeRoundedRect的UIButton ?你不能改变背景颜色。当你尝试改变它的背景色时,你实际上是在改变按钮所绘制的矩形的颜色(通常是清晰的)。有两种方法。您可以子类化UIButton并覆盖它的-drawRect:方法,也可以为不同的按钮状态创建图像(这样做很好)。

If you set the background images in Interface Builder you should notice that IB doesn't support setting images for all the states the button can have, so I recommend setting the images in code like this:

如果你在Interface Builder中设置背景图像,你应该注意到IB不支持为按钮可以设置的所有状态设置图像,所以我建议用如下代码设置图像:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
[myButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
[myButton setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];

The last line shows how to set an image for the selected & highlighted state (that's the one IB can't set). You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.

最后一行显示了如何为选定的和突出显示的状态设置图像(这是IB无法设置的)。如果您是按钮dosn,则不需要选择的图像(第4和第6行)。

#4


27  

Another possibility:

另一种可能性:

  1. Create a UIButton in Interface builder.
  2. 在接口构建器中创建一个UIButton。
  3. Give it a type 'Custom'
  4. 输入" Custom "
  5. Now, in IB it is possible to change the background color
  6. 现在,在IB中可以改变背景颜色

However, the button is square, and that is not what we want. Create an IBOutlet with a reference to this button and add the following to the viewDidLoad method:

但是,按钮是正方形的,这不是我们想要的。创建一个引用此按钮的IBOutlet,并向viewDidLoad方法添加以下内容:

[buttonOutlet.layer setCornerRadius:7.0f];
[buttonOutlet.layer setClipToBounds:YES];

Don't forget to import QuartzCore.h

别忘了导入QuartzCore.h

#5


16  

Subclass UIButton and override setHighlighted and setSelected methods

子类UIButton和覆盖se大灯和setSelected方法

-(void) setHighlighted:(BOOL)highlighted {

  if(highlighted) {
    self.backgroundColor = [self.mainColor darkerShade];
  } else {
    self.backgroundColor = self.mainColor;
  }
  [super setHighlighted:highlighted];
}

-(void) setSelected:(BOOL)selected {

  if(selected) {
    self.backgroundColor = [self.mainColor darkerShade];
  } else {
    self.backgroundColor = self.mainColor;
  }
  [super setSelected:selected];
}

My darkerShade method is in a UIColor category like this

我的darkerShade方法就是像这样利用UIColor

-(UIColor*) darkerShade {

  float red, green, blue, alpha;
  [self getRed:&red green:&green blue:&blue alpha:&alpha];

  double multiplier = 0.8f;
  return [UIColor colorWithRed:red * multiplier green:green * multiplier blue:blue*multiplier alpha:alpha];
}

#6


7  

是否可以改变UIButtons的背景颜色?

If you are not wanting to use images, and want it to look exactly like the Rounded Rect style, try this. Just place a UIView over the UIButton, with an identical frame and auto resize mask, set the alpha to 0.3, and set the background to a color. Then use the snippet below to clip the rounded edges off the colored overlay view. Also, uncheck the 'User Interaction Enabled' checkbox in IB on the UIView to allow touch events to cascade down to the UIButton underneath.

如果您不希望使用图像,并希望它看起来与圆形矩形样式完全相同,请尝试此方法。只需在UIButton上放置一个UIView,具有相同的框架和自动调整大小的蒙版,将alpha设置为0。3,并将背景设置为一个颜色。然后使用下面的代码片段从彩色叠加视图中剪辑圆角边缘。另外,在UIView的IB中取消“用户交互启用”复选框,以允许触摸事件级联到下面的UIButton。

One side effect is that your text will also be colorized.

一个副作用是你的文字也会被着色。

#import <QuartzCore/QuartzCore.h>

colorizeOverlayView.layer.cornerRadius = 10.0f;
colorizeOverlayView.layer.masksToBounds = YES;

#7


7  

Another possibility (the best and most beautiful imho):

另一种可能(最美的和最美的):

Create a UISegmentedControl with 2 segments in the required background color in Interface Builder. Set the type to 'bar'. Then, change it to having only one segment. Interface builder does not accept one segment so you have to do that programmatically.

创建一个UISegmentedControl,在界面构建器中使用所需的背景色的两个部分。将类型设置为“bar”。然后,将它改为只有一个段。接口构建器不接受一个段,所以必须以编程的方式进行。

Therefore, create an IBOutlet for this button and add this to the viewDidLoad of your view:

因此,为这个按钮创建一个IBOutlet,并将其添加到视图的viewDidLoad中:

[segmentedButton removeSegmentAtIndex:1 animated:NO];

Now you have a beautiful glossy, colored button with the specified background color. For actions, use the 'value changed' event.

现在,您有了一个漂亮的有光泽的,有颜色的按钮与指定的背景颜色。对于操作,使用“值更改”事件。

(I have found this on http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/). Thanks Chris!

(我在http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/上找到的)。谢谢克里斯!

#8


5  

Well I'm 99% percent positive that you cannot just go and change the background color of a UIButton. Instead you have to go and change the background images yourself which I think is a pain. I'm amazed that I had to do this.

99%肯定的是你不能改变UIButton的背景颜色。相反,你必须自己去改变背景图片,我觉得这很痛苦。我很惊讶我必须这么做。

If I'm wrong or if theres a better way without having to set background images please let me know

如果我错了,或者有更好的方法不用设置背景图片,请告诉我

[random setBackgroundImage:[UIImage imageNamed:@"toggleoff.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];


[random setBackgroundImage:[UIImage imageNamed:@"toggleon.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

#9


2  

Per @EthanB suggestion and @karim making a back filled rectangle, I just created a category for the UIButton to achieve this.

根据@EthanB和@karim的建议,我刚刚为UIButton创建了一个类别来实现这一点。

Just drop in the Category code: https://github.com/zmonteca/UIButton-PLColor

只需添加类别代码:https://github.com/zmonteca/UIButton-PLColor

Usage:

用法:

[button setBackgroundColor:uiTextColor forState:UIControlStateDisabled];

Optional forStates to use:

可选forStates使用:

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected

#10


2  

You can also add a CALayer to the button - you can do lots of things with these including a color overlay, this example uses a plain color layer you can also easily graduate the colour. Be aware though added layers obscure those underneath

你也可以在按钮上添加一个CALayer -你可以用这些来做很多事情,包括颜色叠加,这个例子使用一个纯色层,你也可以很容易地渐变颜色。但是要注意,添加的图层会使下面的图层模糊

+(void)makeButtonColored:(UIButton*)button color1:(UIColor*) color
{

    CALayer *layer = button.layer;
    layer.cornerRadius = 8.0f;
    layer.masksToBounds = YES;
    layer.borderWidth = 4.0f;
    layer.opacity = .3;//
    layer.borderColor = [UIColor colorWithWhite:0.4f alpha:0.2f].CGColor;

    CAGradientLayer *colorLayer = [CAGradientLayer layer];
    colorLayer.cornerRadius = 8.0f;
    colorLayer.frame = button.layer.bounds;
    //set gradient colors
    colorLayer.colors = [NSArray arrayWithObjects:
                         (id) color.CGColor,
                         (id) color.CGColor,
                         nil];

    //set gradient locations
    colorLayer.locations = [NSArray arrayWithObjects:
                            [NSNumber numberWithFloat:0.0f],
                            [NSNumber numberWithFloat:1.0f],
                            nil];


    [button.layer addSublayer:colorLayer];

}

#11


1  

add a second target for the UIButton for UIControlEventTouched and change the UIButton background color. Then change it back in the UIControlEventTouchUpInside target;

为uicontroleventtouch添加第二个目标,并更改UIButton的背景颜色。然后在UIControlEventTouchUpInside目标中改变它;

#12


1  

For professional and nice looking buttons, you may check this custom button component. You can use it directly in your views and tableviews or modify the source code to make it meet your needs. Hope this helps.

对于专业和美观的按钮,您可以检查这个自定义按钮组件。您可以在视图和表视图中直接使用它,或者修改源代码以满足您的需要。希望这个有帮助。

#13


1  

This isn't as elegant as sub-classing UIButton, however if you just want something quick - what I did was create custom button, then a 1px by 1px image with the colour I'd want the button to be, and set the background of the button to that image for the highlighted state - works for my needs.

这不是生成子类UIButton一样优雅,但是如果你只是想要快——我所做的是创建自定义按钮,然后由1 px 1 px图像的颜色我想让按钮,并设置背景图片的按钮高亮显示的状态——适合我的需要。

#14


1  

I know this was asked a long time ago and now there's a new UIButtonTypeSystem. But newer questions are being marked as duplicates of this question so here's my newer answer in the context of an iOS 7 system button, use the .tintColor property.

我知道这是很久以前问的现在有一个新的UIButtonTypeSystem。但是更新的问题被标记为这个问题的重复,所以这是我在ios7系统按钮上下文中更新的答案,使用。tintcolor属性。

let button = UIButton(type: .System)
button.setTitle("My Button", forState: .Normal)
button.tintColor = .redColor()

#15


0  

[myButton setBackgroundColor:[UIColor blueColor]]; [myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

[myButton setBackgroundColor:[用户界面颜色blueColor]];[myButton setTitleColor:[用户界面颜色whiteColor]forState:UIControlStateNormal);

It's possible change this way or going on Storyboard and change background on options in right side.

有可能以这种方式改变或者进入故事板,改变右边选项的背景。

#16


0  

Swift 3:

斯威夫特3:

        static func imageFromColor(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage {
            let rect = CGRect(x: 0, y: 0, width: width, height: height);
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()!
            context.setFillColor(color.cgColor)
            context.fill(rect)
            let img = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return img;
        }

        let button = UIButton(type: .system)
        let image = imageFromColor(color: .red, width: 
        button.frame.size.width, height: button.frame.size.height)
        button.setBackgroundImage(image, for: .normal)

#1


155  

This can be done programmatically by making a replica:

可以通过编程方式创建副本:

    loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    loginButton.backgroundColor = [UIColor whiteColor];
    loginButton.layer.borderColor = [UIColor blackColor].CGColor;
    loginButton.layer.borderWidth = 0.5f;
    loginButton.layer.cornerRadius = 10.0f;

edit: ofcourse, you'd have to #import <QuartzCore/QuartzCore.h>

编辑:当然,你需要#import

edit: to all new readers, you should also consider a few options added as "another possibility". for you consideration.

编辑:对于所有的新读者,你也应该考虑添加一些选项作为“另一种可能性”。为你考虑。

As this is an old answer, I strongly recommend reading comments for troubleshooting

由于这是一个旧的答案,我强烈推荐阅读评论来排除故障。

#2


59  

I have a different approach,

我有不同的方法,

[btFind setTitle:NSLocalizedString(@"Find", @"") forState:UIControlStateNormal];    
[btFind setBackgroundImage:[CommonUIUtility imageFromColor:[UIColor cyanColor]] 
        forState:UIControlStateNormal];
btFind.layer.cornerRadius = 8.0;
btFind.layer.masksToBounds = YES;
btFind.layer.borderColor = [UIColor lightGrayColor].CGColor;
btFind.layer.borderWidth = 1;

From CommonUIUtility,

从CommonUIUtility,

+ (UIImage *) imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    //  [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ;
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Don't forget to #import <QuartzCore/QuartzCore.h>

不要忘记#import

#3


32  

I assume you're talking about a UIButton with UIButtonTypeRoundedRect? You can't change the background color of that. When you try changing it's background color you're rather changing the color of the rect the button is drawn on (which is usually clear). So there are two ways to go. Either you subclass UIButton and overwrite its -drawRect: method or you create images for the different button states (which is perfectly fine to do).

我想你说的是带有UIButtonTypeRoundedRect的UIButton ?你不能改变背景颜色。当你尝试改变它的背景色时,你实际上是在改变按钮所绘制的矩形的颜色(通常是清晰的)。有两种方法。您可以子类化UIButton并覆盖它的-drawRect:方法,也可以为不同的按钮状态创建图像(这样做很好)。

If you set the background images in Interface Builder you should notice that IB doesn't support setting images for all the states the button can have, so I recommend setting the images in code like this:

如果你在Interface Builder中设置背景图像,你应该注意到IB不支持为按钮可以设置的所有状态设置图像,所以我建议用如下代码设置图像:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
[myButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
[myButton setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];

The last line shows how to set an image for the selected & highlighted state (that's the one IB can't set). You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.

最后一行显示了如何为选定的和突出显示的状态设置图像(这是IB无法设置的)。如果您是按钮dosn,则不需要选择的图像(第4和第6行)。

#4


27  

Another possibility:

另一种可能性:

  1. Create a UIButton in Interface builder.
  2. 在接口构建器中创建一个UIButton。
  3. Give it a type 'Custom'
  4. 输入" Custom "
  5. Now, in IB it is possible to change the background color
  6. 现在,在IB中可以改变背景颜色

However, the button is square, and that is not what we want. Create an IBOutlet with a reference to this button and add the following to the viewDidLoad method:

但是,按钮是正方形的,这不是我们想要的。创建一个引用此按钮的IBOutlet,并向viewDidLoad方法添加以下内容:

[buttonOutlet.layer setCornerRadius:7.0f];
[buttonOutlet.layer setClipToBounds:YES];

Don't forget to import QuartzCore.h

别忘了导入QuartzCore.h

#5


16  

Subclass UIButton and override setHighlighted and setSelected methods

子类UIButton和覆盖se大灯和setSelected方法

-(void) setHighlighted:(BOOL)highlighted {

  if(highlighted) {
    self.backgroundColor = [self.mainColor darkerShade];
  } else {
    self.backgroundColor = self.mainColor;
  }
  [super setHighlighted:highlighted];
}

-(void) setSelected:(BOOL)selected {

  if(selected) {
    self.backgroundColor = [self.mainColor darkerShade];
  } else {
    self.backgroundColor = self.mainColor;
  }
  [super setSelected:selected];
}

My darkerShade method is in a UIColor category like this

我的darkerShade方法就是像这样利用UIColor

-(UIColor*) darkerShade {

  float red, green, blue, alpha;
  [self getRed:&red green:&green blue:&blue alpha:&alpha];

  double multiplier = 0.8f;
  return [UIColor colorWithRed:red * multiplier green:green * multiplier blue:blue*multiplier alpha:alpha];
}

#6


7  

是否可以改变UIButtons的背景颜色?

If you are not wanting to use images, and want it to look exactly like the Rounded Rect style, try this. Just place a UIView over the UIButton, with an identical frame and auto resize mask, set the alpha to 0.3, and set the background to a color. Then use the snippet below to clip the rounded edges off the colored overlay view. Also, uncheck the 'User Interaction Enabled' checkbox in IB on the UIView to allow touch events to cascade down to the UIButton underneath.

如果您不希望使用图像,并希望它看起来与圆形矩形样式完全相同,请尝试此方法。只需在UIButton上放置一个UIView,具有相同的框架和自动调整大小的蒙版,将alpha设置为0。3,并将背景设置为一个颜色。然后使用下面的代码片段从彩色叠加视图中剪辑圆角边缘。另外,在UIView的IB中取消“用户交互启用”复选框,以允许触摸事件级联到下面的UIButton。

One side effect is that your text will also be colorized.

一个副作用是你的文字也会被着色。

#import <QuartzCore/QuartzCore.h>

colorizeOverlayView.layer.cornerRadius = 10.0f;
colorizeOverlayView.layer.masksToBounds = YES;

#7


7  

Another possibility (the best and most beautiful imho):

另一种可能(最美的和最美的):

Create a UISegmentedControl with 2 segments in the required background color in Interface Builder. Set the type to 'bar'. Then, change it to having only one segment. Interface builder does not accept one segment so you have to do that programmatically.

创建一个UISegmentedControl,在界面构建器中使用所需的背景色的两个部分。将类型设置为“bar”。然后,将它改为只有一个段。接口构建器不接受一个段,所以必须以编程的方式进行。

Therefore, create an IBOutlet for this button and add this to the viewDidLoad of your view:

因此,为这个按钮创建一个IBOutlet,并将其添加到视图的viewDidLoad中:

[segmentedButton removeSegmentAtIndex:1 animated:NO];

Now you have a beautiful glossy, colored button with the specified background color. For actions, use the 'value changed' event.

现在,您有了一个漂亮的有光泽的,有颜色的按钮与指定的背景颜色。对于操作,使用“值更改”事件。

(I have found this on http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/). Thanks Chris!

(我在http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/上找到的)。谢谢克里斯!

#8


5  

Well I'm 99% percent positive that you cannot just go and change the background color of a UIButton. Instead you have to go and change the background images yourself which I think is a pain. I'm amazed that I had to do this.

99%肯定的是你不能改变UIButton的背景颜色。相反,你必须自己去改变背景图片,我觉得这很痛苦。我很惊讶我必须这么做。

If I'm wrong or if theres a better way without having to set background images please let me know

如果我错了,或者有更好的方法不用设置背景图片,请告诉我

[random setBackgroundImage:[UIImage imageNamed:@"toggleoff.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];


[random setBackgroundImage:[UIImage imageNamed:@"toggleon.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

#9


2  

Per @EthanB suggestion and @karim making a back filled rectangle, I just created a category for the UIButton to achieve this.

根据@EthanB和@karim的建议,我刚刚为UIButton创建了一个类别来实现这一点。

Just drop in the Category code: https://github.com/zmonteca/UIButton-PLColor

只需添加类别代码:https://github.com/zmonteca/UIButton-PLColor

Usage:

用法:

[button setBackgroundColor:uiTextColor forState:UIControlStateDisabled];

Optional forStates to use:

可选forStates使用:

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected

#10


2  

You can also add a CALayer to the button - you can do lots of things with these including a color overlay, this example uses a plain color layer you can also easily graduate the colour. Be aware though added layers obscure those underneath

你也可以在按钮上添加一个CALayer -你可以用这些来做很多事情,包括颜色叠加,这个例子使用一个纯色层,你也可以很容易地渐变颜色。但是要注意,添加的图层会使下面的图层模糊

+(void)makeButtonColored:(UIButton*)button color1:(UIColor*) color
{

    CALayer *layer = button.layer;
    layer.cornerRadius = 8.0f;
    layer.masksToBounds = YES;
    layer.borderWidth = 4.0f;
    layer.opacity = .3;//
    layer.borderColor = [UIColor colorWithWhite:0.4f alpha:0.2f].CGColor;

    CAGradientLayer *colorLayer = [CAGradientLayer layer];
    colorLayer.cornerRadius = 8.0f;
    colorLayer.frame = button.layer.bounds;
    //set gradient colors
    colorLayer.colors = [NSArray arrayWithObjects:
                         (id) color.CGColor,
                         (id) color.CGColor,
                         nil];

    //set gradient locations
    colorLayer.locations = [NSArray arrayWithObjects:
                            [NSNumber numberWithFloat:0.0f],
                            [NSNumber numberWithFloat:1.0f],
                            nil];


    [button.layer addSublayer:colorLayer];

}

#11


1  

add a second target for the UIButton for UIControlEventTouched and change the UIButton background color. Then change it back in the UIControlEventTouchUpInside target;

为uicontroleventtouch添加第二个目标,并更改UIButton的背景颜色。然后在UIControlEventTouchUpInside目标中改变它;

#12


1  

For professional and nice looking buttons, you may check this custom button component. You can use it directly in your views and tableviews or modify the source code to make it meet your needs. Hope this helps.

对于专业和美观的按钮,您可以检查这个自定义按钮组件。您可以在视图和表视图中直接使用它,或者修改源代码以满足您的需要。希望这个有帮助。

#13


1  

This isn't as elegant as sub-classing UIButton, however if you just want something quick - what I did was create custom button, then a 1px by 1px image with the colour I'd want the button to be, and set the background of the button to that image for the highlighted state - works for my needs.

这不是生成子类UIButton一样优雅,但是如果你只是想要快——我所做的是创建自定义按钮,然后由1 px 1 px图像的颜色我想让按钮,并设置背景图片的按钮高亮显示的状态——适合我的需要。

#14


1  

I know this was asked a long time ago and now there's a new UIButtonTypeSystem. But newer questions are being marked as duplicates of this question so here's my newer answer in the context of an iOS 7 system button, use the .tintColor property.

我知道这是很久以前问的现在有一个新的UIButtonTypeSystem。但是更新的问题被标记为这个问题的重复,所以这是我在ios7系统按钮上下文中更新的答案,使用。tintcolor属性。

let button = UIButton(type: .System)
button.setTitle("My Button", forState: .Normal)
button.tintColor = .redColor()

#15


0  

[myButton setBackgroundColor:[UIColor blueColor]]; [myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

[myButton setBackgroundColor:[用户界面颜色blueColor]];[myButton setTitleColor:[用户界面颜色whiteColor]forState:UIControlStateNormal);

It's possible change this way or going on Storyboard and change background on options in right side.

有可能以这种方式改变或者进入故事板,改变右边选项的背景。

#16


0  

Swift 3:

斯威夫特3:

        static func imageFromColor(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage {
            let rect = CGRect(x: 0, y: 0, width: width, height: height);
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()!
            context.setFillColor(color.cgColor)
            context.fill(rect)
            let img = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return img;
        }

        let button = UIButton(type: .system)
        let image = imageFromColor(color: .red, width: 
        button.frame.size.width, height: button.frame.size.height)
        button.setBackgroundImage(image, for: .normal)