2011-08-30 58 views

回答

6
[mBtn setTintColor:[UIColor grayColor]]; 

這隻影響突出顯示的狀態,所以我相信這就是您要找的。

您也可以從Interface Builder中將其設置爲突出顯示色調下拉菜單。

+0

這是不行的,我得到「的UIButton」不能爲「-setTintColor:」應對 「的UIButton」可不迴應「setTintColor:」 – Syntax

+0

你說得對,我再次檢查,並針對iOS這隻作品5.0及更高版本。在這種情況下,您將不得不創建一個UIView,設置其背景色,並將此視圖用作突出顯示狀態的背景圖像。 – antalkerekes

+0

沒問題,我會給iOS 5一個去。 – Syntax

0

有這樣的沒有方法,setBackgroundColor:forState:

檢查文檔。你需要使用圖像。

+1

那就有點傻了,不得不加載一個圖像只是爲了換色。 – Syntax

+0

@syntax對不起,兄弟,你沒有選擇。 – Ishu

10

我正在回覆這個舊線程,因爲它在搜索此問題的解決方案時一直彈出,並且我在其他地方看不到任何解決方案。 setTintColor只適用於UIButton的突出顯示狀態,這實在令人煩惱。六個月前,它同樣令人討厭,它只適用於iOS 5,但希望未來可能不會成爲一個問題。考慮到這一點,我已經利用並結合了一些社區建議,將通用解決方案組合爲正常狀態下的一組按鈕。

下面的方法接受一個UIButtons的NSArray和一組顏色規範作爲輸入。它使用setTintColor將顏色規範應用於一個按鈕,將結果呈現爲UIImage,並將該圖像用作整組按鈕的背景圖像。這避免了爲按鈕顏色創建離散圖像文件的需要。此外,它使用可拉伸的圖像,以便它可以處理不同大小的按鈕集合(儘管請注意,它假設UIButton的默認邊角舍入因子)。我希望你會發現它適用於iOS 5的目標。

- (void) setColorOfButtons:(NSArray*)buttons red:(float)red green:(float)green blue:(float)blue alpha:(float)alpha { 

    if (buttons.count == 0) { 
     return; 
    } 

    // get the first button 
    NSEnumerator* buttonEnum = [buttons objectEnumerator]; 
    UIButton* button = (UIButton*)[buttonEnum nextObject]; 

    // set the button's highlight color 
    [button setTintColor:[UIColor colorWithRed:red/255.9999f green:green/255.9999f blue:blue/255.9999f alpha:alpha]]; 

    // clear any existing background image 
    [button setBackgroundImage:nil forState:UIControlStateNormal]; 

    // place the button into highlighted state with no title 
    BOOL wasHighlighted = button.highlighted; 
    NSString* savedTitle = [button titleForState:UIControlStateNormal]; 
    [button setTitle:nil forState:UIControlStateNormal]; 
    [button setHighlighted:YES]; 

    // render the highlighted state of the button into an image 
    UIGraphicsBeginImageContext(button.layer.frame.size); 
    CGContextRef graphicsContext = UIGraphicsGetCurrentContext(); 
    [button.layer renderInContext:graphicsContext]; 
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIImage* stretchableImage = [image stretchableImageWithLeftCapWidth:12 topCapHeight:0]; 
    UIGraphicsEndImageContext(); 

    // restore the button's state and title 
    [button setHighlighted:wasHighlighted]; 
    [button setTitle:savedTitle forState:UIControlStateNormal]; 

    // set background image of all buttons 
    do { 
     [button setBackgroundImage:stretchableImage forState:UIControlStateNormal]; 
    } while (button = (UIButton*)[buttonEnum nextObject]);  
} 
+1

請注意,'[button titleForState:UIControlStateNormal]'可能會返回無效對象,當它沒有設置(例如,當通過IB工作時),對於我改變這一行爲'NSString savedTitle = [button titleLabel] .text;'工程,所以你可能要添加一個檢查,雖然我不確定檢查應該在那裏(因爲它不返回nil,它會返回一個INVALID對象,如果未設置標題,將會崩潰) – 2012-07-31 07:52:59

+0

感謝您的Tipp ishaq。面對完全相同的問題... –

4

只是對於像我改變背景顏色爲亮狀態搜索時,也將在這裏着陸......

我結束了與具有backgroundHighlightColor和軌道突出通過屬性的子類的UIButton志願。以下是GitHub的鏈接:SOHighlightButton

如果您需要更多/其他屬性,或者突出顯示更改UIButton的其他屬性,您應該可以將其調整爲任何其他方案。