2011-08-30 60 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的其他属性,您应该可以将其调整为任何其他方案。