如何以编程方式更改uibutton的背景颜色

时间:2012-05-08 06:24:02

标签: ios uikit

我想将按钮的背景颜色更改为黑色。

我尝试了很多代码。但是效果不好。

我该怎么做?

7 个答案:

答案 0 :(得分:3)

我认为这会对你有帮助,

[button setBackgroundColor:[UIColor redColor]];

答案 1 :(得分:3)

如果您想以编程方式更改按钮的颜色,则必须将按钮类型设置为自定义: -

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

然后您可以按[btn setBackgroundColor:[UIColor blackColor]];更改背景幕,或者您可以使用steImage上的btn方法设置黑色背景图片。

答案 2 :(得分:2)

白驹先生/请您在下面查看我的代码,

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

我认为它可以帮助您设置背景颜色并为按钮设置背景图像。如果要设置图像,请更改按钮类型RoundedRect to Custom。我希望它会对你有所帮助。感谢。

答案 3 :(得分:1)

使用此行代码并尝试使用任何彩色图像。

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

答案 4 :(得分:1)

如果有人想知道如何使用完整代码在swift中做同样的事情那么这就是......只需在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()
    }

答案 5 :(得分:0)

在您的XIB中拖放一个按钮。得到右侧的按钮属性和将按钮类型设置为自定义。 (或者你也可以在代码中做到)。在.h文件中创建UIButton * btn;并将其绑定到XIB。

然后转到.m文件并在viewdidload方法中使用此代码。

[btn setBackgroundColor:[UIColor blackColor]];

谢谢:)

答案 6 :(得分:0)

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