问题
I want to change the background color of a button to black.
I have tried so many codes. but didn't works fine.
How would I do it?
回答1:
If you want to programatically change the colour of button you will have to make the type of button as custom as :-
UIButton *button = [UIButton buttonWithType:uibuttontypecustom];
note "uibuttontypecustom"
and then you can change backgroung by [btn setBackgroundColor:[UIColor blackColor]]; or you can set a black backgroung image by using steImage method on btn.
回答2:
Mr/Ms Baiju please review below my code,
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];
I think it will help you to set background color and set background image for a button. If you want to set image please change the button type RoundedRect to Custom. I hope it will help you little bit. Thanks.
回答3:
I think this will help you,
[button setBackgroundColor:[UIColor redColor]];
回答4:
Use this line of code and try use any color image .
[myButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
回答5:
If anyone wants to know how to make same thing in swift with full code then here it is...Just write this code in your 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()
}
回答6:
in your XIB drag and drop a button. got to button properties in your right hand side and set button type to custom. (Or you can do than in code too). In your .h file create UIButton * btn; and bind it to the XIB.
Then go to .m file and in viewdidload method right this code.
[btn setBackgroundColor:[UIColor blackColor]];
Thanks :)
回答7:
Change the layer colour e.g. self.btn.layer.backgroundColor = [UIColor redColor].CGColor;
来源:https://stackoverflow.com/questions/10493600/how-to-change-backgroundcolor-of-uibutton-programatically