Syn*_*tax 5 objective-c uicolor
我正在尝试更改按钮的背景颜色,当它被选中并且不想使用图像时.
[mBtn setBackgroundColor:[UIColor grayColor] forState:UIControlStateHighlighted];
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
Sco*_*uta 10
我正在回复这个旧线程,因为它在搜索此问题的解决方案时一直弹出,我在其他地方看不到任何解决方案.setTintColor仅适用于UIButton的突出显示状态,这真是令人讨厌.六个月前,同样令人讨厌的是它只适用于iOS 5,但希望这不会成为未来的问题.考虑到这一点,我已经利用并结合了许多社区建议来组合一个通用解决方案,以便在正常状态下对一组按钮进行着色.
下面的方法接受UIButton的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]);
}
Run Code Online (Sandbox Code Playgroud)
[mBtn setTintColor:[UIColor grayColor]];
Run Code Online (Sandbox Code Playgroud)
这只会影响突出显示的状态,所以我相信这就是你要找的东西.
您也可以从" 突出显示色调"下拉菜单中的" 界面生成器"进行设置.
| 归档时间: |
|
| 查看次数: |
17703 次 |
| 最近记录: |