简体   繁体   English

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

[英]Is it possible to change a UIButtons background color?

This one has me stumped.这个难倒我了。

Is it possible at all to change the background color of a UIButton in Cocoa for iPhone.是否可以在 Cocoa for iPhone 中更改 UIButton 的背景颜色。 I've tried setting the background color but it only changes the corners.我试过设置背景颜色,但它只改变角落。 setBackgroundColor: seems to be the only method available for such things. setBackgroundColor:似乎是唯一可用于此类事情的方法。

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

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: of course, you'd have to #import <QuartzCore/QuartzCore.h>编辑:当然,你必须#import <QuartzCore/QuartzCore.h>

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由于这是一个旧答案,我强烈建议阅读评论以进行故障排除

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 <QuartzCore/QuartzCore.h>

I assume you're talking about a UIButton with UIButtonTypeRoundedRect ?我假设您正在谈论带有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).要么-drawRect: 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).最后一行显示了如何为选定和突出显示的状态设置图像(这是 IB 无法设置的)。 You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.如果您的按钮不需要选定状态,则您不需要选定的图像(第 4 行和第 6 行)。

Another possibility:另一种可能:

  1. Create a UIButton in Interface builder.在界面生成器中创建一个 UIButton。
  2. Give it a type 'Custom'给它一个类型“自定义”
  3. Now, in IB it is possible to change the background color现在,在 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

Subclass UIButton and override setHighlighted and setSelected methods子类化 UIButton 并覆盖 setHighlighted 和 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];
}

Another possibility (the best and most beautiful imho):另一种可能性(最好和最美丽的恕我直言):

Create a UISegmentedControl with 2 segments in the required background color in Interface Builder.在界面生成器中以所需的背景颜色创建一个带有 2 个段的 UISegmentedControl。 Set the type to 'bar'.将类型设置为“bar”。 Then, change it to having only one segment.然后,将其更改为只有一个段。 Interface builder does not accept one segment so you have to do that programmatically.界面生成器不接受一个段,因此您必须以编程方式执行此操作。

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/ ). (我在http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/上找到了这个)。 Thanks Chris!谢谢克里斯!

彩色 UIButton

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.只需在 UIButton 上放置一个 UIView,使用相同的框架和自动调整大小蒙版,将 alpha 设置为 0.3,并将背景设置为一种颜色。 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.此外,取消选中 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;

Well I'm 99% percent positive that you cannot just go and change the background color of a UIButton.嗯,我 99% 的肯定你不能只是去改变 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.我很惊讶我必须这样做。

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

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.您还可以向按钮添加 CALayer - 您可以使用这些进行很多操作,包括颜色叠加,此示例使用纯色图层,您也可以轻松地对颜色进行渐变。 Be aware though added layers obscure those underneath请注意,虽然添加的图层会掩盖下面的图层

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

}

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:可选的状态使用:

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected

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.希望这可以帮助。

这不像子类化 UIButton 那样优雅,但是如果你只是想要一些快速的东西 - 我所做的是创建自定义按钮,然后是一个 1px x 1px 的图像,它的颜色是我想要的按钮,然后设置背景用于突出显示状态的该图像的按钮 - 适合我的需要。

I know this was asked a long time ago and now there's a new UIButtonTypeSystem.我知道很久以前就有人问过这个问题,现在有一个新的 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.但是较新的问题被标记为这个问题的重复,所以这是我在 iOS 7 系统按钮上下文中的较新答案,使用.tintColor属性。

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

add a second target for the UIButton for UIControlEventTouched and change the UIButton background color.UIControlEventTouchedUIButton添加第二个目标并更改UIButton背景颜色。 Then change it back in the UIControlEventTouchUpInside target;然后在UIControlEventTouchUpInside目标中将其改回;

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

可以通过这种方式进行更改,也可以在 Storyboard 中更改右侧选项的背景。

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)

For iOS 15+ Apple provides a simple button configuration to accomplish this.对于 iOS 15+,Apple 提供了一个简单的按钮配置来完成此操作。

Objective-C:目标-C:

randomButton.configuration = [UIButtonConfiguration filledButtonConfiguration];

Swift:迅速:

randomButton.configuration = .filled()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM