2010-05-11 98 views
100

這一個讓我難住。是否可以更改UIButtons背景顏色?

是否有可能在iOS可可改變UIButton的背景顏色。 我試過設置背景顏色,但它只是改變了角落。似乎是唯一可用於這種事情的方法。

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

可以修復的圖像,或將其刪除? kthx;) – stigi 2010-05-11 11:20:33

+0

o-0 hmmmm ....., 圖像很好,但現在它不會再顯示出來。剛刪除它 – dubbeat 2010-05-11 11:58:29

+0

這是一個重複的http://stackoverflow.com/questions/372731/how-can-i-set-a-button-background-color-on-iphone – 2010-05-11 12:38:43

回答

154

這可以通過編程製作的複製品來完成:

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; 

編輯:ofcourse,你必須#import <QuartzCore/QuartzCore.h>

編輯:所有的新讀者,你也應該考慮增加一些選項作爲「另一種可能性」。爲你考慮。

由於這是一個古老的答案,我強烈建議您閱讀評論的故障排除

+0

我試過你的代碼,但它沒有爲我工作 – pankaj 2011-04-23 12:11:25

+3

沒有工作,或者你沒有得到預期的結果? – 2011-04-24 20:41:32

+1

最佳答案石英FTW – 2011-05-21 03:53:48

5

那麼我99%的積極,你不能只是去改變UIButton的背景顏色。相反,你必須自己去改變背景圖片,我認爲這是一種痛苦。我很驚訝我必須這樣做。

如果我錯了,或者如果那裏有一個更好的辦法,而無需設置背景圖片,請讓我知道

[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]; 
+4

你是對的。這是一種痛苦,應該花幾分鐘的時間去做,而不是創造圖像的麻煩。另外如果你的按鈕是圓形的,那麼它就更難以做到了......這樣的痛苦。 – 2011-08-07 17:00:42

32

我假設你是在談論一個UIButton與UIButtonTypeRoundedRect? 你不能改變它的背景顏色。當你嘗試改變它的背景顏色時,你只是改變矩形的顏色,這個按鈕被繪製在上面(通常很清晰)。 所以有兩種方法。要麼你繼承UIButton並覆蓋它的-drawRect:方法,要麼爲不同的按鈕狀態創建圖像(這非常好)。

如果您在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)]; 

最後一行顯示如何爲選定的&突出顯示的狀態(這是一個IB無法設置)設置圖像。 如果您按鈕不需要選定狀態,則不需要所選圖像(第4行& 6)。

+0

感謝您的解釋。只是一個簡單的問題。如果我正在覆蓋drawrect方法,那麼我想這會涉及到使用繪圖庫嗎? 單獨使用編程方式繪製圓角矩形並用顏色填充它的線條? – dubbeat 2010-05-11 09:37:17

+2

我只是做了一個簡短的谷歌查詢「iphone drawrect圓角」,並發現這個:http://iphonedevelopment.blogspot.com/2008/11/creating-transparent-uiviews-rounded.html 檢查drawrect方法的一個示例如何繪製圓形矩形。您可以使用'CGContextSetFillColorWithColor'和'CGContextFillPath'來填充'CGContextAddArcToPoint'繪製的路徑。 – stigi 2010-05-11 09:53:47

+0

太好了。非常感謝 – dubbeat 2010-05-11 10:17:34

1

添加第二個目標爲UIButtonUIControlEventTouched,改變UIButton背景顏色。然後將其更改回UIControlEventTouchUpInside目標;

7

colored UIButton

如果你不想使用的圖片,並希望它看起來就像圓角的矩形風格,試試這個。只需在UIButton上放置一個UIView,使用相同的框架和自動調整大小的蒙版,將alpha設置爲0.3,並將背景設置爲一種顏色。然後使用下面的代碼片段將彩色覆蓋視圖中的圓形邊緣剪下。此外,取消選中UIView中IB中的「User Interaction Enabled」複選框,以允許觸摸事件級聯到下面的UIButton。

一個副作用是,您的文本也會着色。

#import <QuartzCore/QuartzCore.h> 

colorizeOverlayView.layer.cornerRadius = 10.0f; 
colorizeOverlayView.layer.masksToBounds = YES; 
59

我有不同的方法,

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

從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; 
} 

不要忘了#import <QuartzCore/QuartzCore.h>

+2

不錯。我發現我不得不添加'btFind.layer.borderWidth = 1;' – DefenestrationDay 2012-02-27 22:05:58

+0

我喜歡這個解決方案,但目前我無法使用它。我收到一個錯誤,因爲找不到「CommonUIUtility」。谷歌只是給我日蝕的東西,但我想它應該在QuartzCore中? 有什麼建議嗎? – Stephan 2012-04-11 09:37:12

+0

不,這是用戶定義的類,用於在應用中執行常見的UI事物。你在自己的類中編寫imageFromColor方法。 – karim 2012-04-15 09:24:24

26

另一種可能性:

  1. 在「界面」構建器中創建一個UIButton。
  2. 給它一個類型的「自定義」現在
  3. ,在IB可以改變背景顏色

但是,按鈕是方形的,而這不是我們想要的。與此按鈕的引用創建一個IBOutlet,並添加以下到viewDidLoad方法:

[buttonOutlet.layer setCornerRadius:7.0f]; 
[buttonOutlet.layer setClipToBounds:YES]; 

不要忘了導入QuartzCore.h

+7

完美,謝謝!我不確定是否因爲我使用的iOS版本(5.1),但setClipToBounds不可用。相反,我用buttonOutlet.layer.masksToBounds = TRUE; – iforce2d 2012-05-15 18:30:31

+0

當我添加此代碼時,它顯示一個圓角矩形,但是當我點擊它時,該按鈕不會反轉高光。到底是怎麼回事? – Will 2013-02-05 18:41:49

+0

這種方法的問題是,您無法爲按鈕的突出顯示狀態設置背景顏色。 – ch3rryc0ke 2013-06-25 01:24:29

7

另一種可能性(最好和最美麗恕我直言):

在界面構建器中使用所需背景顏色中的2段創建UISegmentedControl。將類型設置爲「欄」。然後,將其更改爲只有一個細分。界面構建器不接受一個段,因此您必須以編程方式執行該操作。

因此,對於此按鈕創建一個IBOutlet,並添加到您的視圖的viewDidLoad中:

[segmentedButton removeSegmentAtIndex:1 animated:NO]; 

現在你有一個指定的背景顏色美麗的光澤,顏色的按鈕。 對於操作,請使用「值已更改」事件。

(我發現這在http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/)。謝謝克里斯!

16

子類的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]; 
} 

我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]; 
} 
1

對於專業和漂亮的按鈕,你可以檢查這個custom button component。您可以直接在視圖和表格中使用它,或修改源代碼以使其滿足您的需求。希望這可以幫助。

2

您也可以將CALayer添加到按鈕 - 您可以使用包括顏色疊加層在內的許多功能進行操作,本示例使用純色圖層,您也可以輕鬆完成顏色。要知道,雖然加層掩蓋之下的那些

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

} 
+0

輝煌!!!!!!但不能用同一個按鈕多次調用。可以,但新的圖層一次又一次地添加。 – 2013-06-26 19:22:49

+0

@StanJames:對代碼的編輯應該由評論(或者,如果合適的話,由您自己的回答)建議。 – mafso 2014-10-19 19:59:37

1

這並不像子類UIButton的優雅,但是如果你只是想要快速 - 我所做的是創建自定義按鈕,然後一個1x1像素的圖像與我想要的按鈕的顏色,並將按鈕的背景設置爲突出顯示狀態的圖像 - 適合我的需求。

2

Per @EthanB建議和@karim製作一個回填矩形,我只是爲UIButton創建了一個類來實現這個功能。

安上類別代碼:https://github.com/zmonteca/UIButton-PLColor

用法:

[button setBackgroundColor:uiTextColor forState:UIControlStateDisabled]; 

可選forStates使用:

UIControlStateNormal 
UIControlStateHighlighted 
UIControlStateDisabled 
UIControlStateSelected 
1

我知道這是問了很久以前和現在有一個新的UIButtonTypeSystem。但更新的問題被標記爲這個問題的重複,所以這裏是我在iOS 7系統按鈕的上下文中的新答案,使用.tintColor屬性。

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

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

這有可能改變這種方式還是怎麼回事故事板,改變在右側選項的背景。

0

斯威夫特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) 
+0

如果你說過如何調用或使用你在那裏建立的代碼,這將是一個更有用的答案。它是否進入UIButton擴展? – 2017-06-11 06:45:56

+0

@MichaelDautermann添加了使用示例 – pawurb 2017-06-13 08:01:24