[英]How to change backgroundcolor of uibutton programmatically
如何將按鈕的背景顏色更改為黑色?
如果您想以編程方式更改按鈕的顏色,則必須使按鈕的類型自定義為:-
UIButton *button = [UIButton buttonWithType:uibuttontypecustom];
note "uibuttontypecustom"
然后你可以通過[btn setBackgroundColor:[UIColor blackColor]];
改變背景[btn setBackgroundColor:[UIColor blackColor]];
或者您可以通過在btn
上使用steImage
方法設置黑色背景圖像。
我想這會幫助你,
[button setBackgroundColor:[UIColor redColor]];
白居先生/女士請查看下面我的代碼,
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
更改RoundedRect to Custom
。 我希望它會幫助你一點點。 謝謝。
使用這行代碼並嘗試使用任何彩色圖像。
[myButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
如果有人想知道如何使用完整的代碼在 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()
}
在您的 XIB 中拖放一個按鈕。 轉到右側的按鈕屬性並將按鈕類型設置為 custom 。 (或者你也可以用代碼來做)。 在你的 .h 文件中創建UIButton * btn;
並將其綁定到 XIB。
然后轉到 .m 文件並在 viewdidload 方法中正確使用此代碼。
[btn setBackgroundColor:[UIColor blackColor]];
謝謝 :)
更改圖層顏色,例如 self.btn.layer.backgroundColor = [UIColor redColor].CGColor;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.