2012-06-16 135 views
36

我的構建目標設置爲IOS5這是我理解UIButton.tintColor介紹...爲什麼我的UIButton.tintColor不起作用?

我有這個在我viewDidLoad中的視圖控制器

[timelineButton setTintColor:[UIColor blackColor]]; 
[timelineButton setTitle:@"test" forState:UIControlStateNormal]; 

文本適當變化,但按鍵ISN」 t黑色?

謝謝!

+2

根據文檔,「此屬性不適用於所有按鈕類型。」。你使用什麼按鈕類型? –

+0

使用圓角矩形類型 – sayguh

回答

44

按照documentation

此屬性是不是適用於所有類型的按鈕。

您需要將buttonType切換爲另一個one of these。 (不幸的是,文檔沒有指定哪個特定的按鈕類型支持此屬性。)

+1

只需使用標準圓角矩形類型。對此不起作用? – sayguh

+1

顯然不是。 –

+2

它可以在Storyboard/Interface Builder中爲我工作:將按鈕類型設置爲'system',然後將(UIButton的)視圖的背景設置爲所需的顏色 - 完美無缺! –

8

它着色您突出顯示的狀態顏色。 當你點擊/點擊UIButton時,只要按住/點擊UIButton,就會出現用tintColor指定的顏色。

resetButton.tintColor = [UIColor colorWithRed:0.764 green:1.000 blue:0.000 alpha:1.000]; 

該按鈕在正常狀態下爲白色。 但是,如果我點擊按鈕的顏色變成紅色,但只有那樣。

如果您需要更改的按鈕,所以它看起來像一個紅色或藍色的UIControlStateNormal然後

變化在Interface Builder或以編程方式與

UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeCustom]; 

更改UIButtonType到UIButtonTypeCustom的屬性自己並重新創建圓角

resetButton.backgroundColor = [UIColor redColor]; 
resetButton.layer.borderColor = [UIColor blackColor].CGColor; 
resetButton.layer.borderWidth = 0.5f; 
resetButton.layer.cornerRadius = 10.0f; 
+2

並且不要忘記爲CALayer聲明包含#import 。 – zero0cool

+0

讀者應該注意,這是不夠的 - 因爲它是按鈕不會反應,當你觸摸它。你需要連接一些額外的事件來改變按下時的顏色(見下面的alexqinbj的答案)。 –

+0

對我來說,它實際上在正常狀態下工作 – Zaheer

4

今天,我也是mee這個問題。我使用委託來解決它。

[button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchDown]; 
[button addTarget:self action:@selector(buttonPressReset:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside]; 

-(void)buttonPress:(id)sender{ 
UIButton* button = (UIButton*)sender; 
[button setBackgroundColor:[UIColor greenColor]]; 
NSLog(@"buttonPressed"); 
} 

-(void)buttonPressReset:(id)sender{ 
UIButton* button = (UIButton*)sender; 
[button setBackgroundColor:[UIColor redColor]]; 
NSLog(@"buttonPressReset"); 
} 
+0

這不完全 - 你還應該添加UIControlEventTouchDragEnter到觸發buttonPress的事件,並且UIControlEventTouchDragExit觸發buttonPressReset的事件。 –

6

正如其他答案中所述,tint對於自定義按鈕類型不起作用。確保你明確地聲明瞭按鈕類型。不要只用[UIButton的頁頭] INIT]

這將工作:

UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[mybutton setImage:[UIImage imageNamed:@"myImage"] forState:UIControlStateNormal]; 
mybutton.tintColor = [ODTheme blueTintColor]; 
22

確保您的按鈕 「類型」 設置爲系統。如果它設置爲自定義,則可能是按鈕顏色不變的原因。這是發生在我身上的事情,並將類型更改爲系統修復它。

2

應該試試這個方法:

- (void)setTitleColor:(UIColor *)color 
      forState:(UIControlState)state 
2

只需設置你的UIButton故事板鍵入系統

enter image description here

然後在代碼只需使用:

myButton.tintColor = UIColor.whiteColor() 
1

如果您的UIButton類型是系統,那麼只有色彩屬性是工作。所以首先你需要將你的按鈕類型設置爲系統,然後爲特定狀態應用色調。

btn.buttonType = UIButtonTypeSystem; 
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; 
1

我發現必須遵守3件事。

1渲染圖像Default

轉到Images.xcassets > Your Image > Show the Attributes inspector > Render As > Default

render as default

2.確保您的按鈕類型系統

3.現在更改按鈕的tintColor 。

完成。