如何以编程方式更改uibutton的backgroundcolor

我想将button的背景颜色改为黑色。

我已经尝试了这么多的代码。 但没有正常工作。

我该怎么做?

我想这会帮助你,

[button setBackgroundColor:[UIColor redColor]]; 

如果你想以编程方式改变button的颜色,你将不得不按照自定义button的types: –

 UIButton *button = [UIButton buttonWithType:uibuttontypecustom]; note "uibuttontypecustom" 

然后你可以通过[btn setBackgroundColor:[UIColor blackColor]];改变背景[btn setBackgroundColor:[UIColor blackColor]]; 或者您可以在btn上使用steImage方法设置黑色背景图像。

白先生/小姐请在我的代码下面查看,

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(10, 200, 300, 40); [button setTitle:@"Button" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside]; [button setBackgroundColor:[UIColor blackColor]]; [button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal]; [self.view addSubview: button]; 

我认为这将帮助你设置背景颜色和设置button的背景图像。 如果你想设置图像,请将buttontypesRoundedRect to Custom更改RoundedRect to Custom 。 我希望它能帮助你一点点。 谢谢。

使用这一行代码,并尝试使用任何彩色图像。

 [myButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal]; 

如果有人想知道如何使用完整的代码迅速做出同样的事情,那么这里是…只要在你的ViewController.swift

 import UIKit class ViewController: UIViewController { var firstbutton:UIButton? //firstbutton = Your Button Name override func viewDidLoad() { super.viewDidLoad() self.firstbutton = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton self.firstbutton!.frame = CGRectMake(100, 200, 100, 100) //This Line is used for color of your button self.firstbutton!.backgroundColor = UIColor.redColor() self.view.addSubview(firstbutton!) } //This section is used to bring the button in front of everything on the view override func viewDidAppear(animated: Bool) { self.view.bringSubviewToFront(self.firstbutton!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } 

在你的XIB中拖放一个button。 得到button右侧的属性, 并将buttontypes设置为自定义 。 (或者你也可以在代码中做)。 在你的.h文件中创buildUIButton * btn; 并将其绑定到XIB。

然后转到.m文件,并在viewdidload方法的这个代码。

 [btn setBackgroundColor:[UIColor blackColor]]; 

谢谢 :)

更改图层的颜色,例如self.btn.layer.backgroundColor = [UIColor redColor] .CGColor;