gpt4 book ai didi

objective-c - 更改 StateHighlighted 上的圆形矩形按钮背景颜色

转载 作者:太空狗 更新时间:2023-10-30 03:46:48 26 4
gpt4 key购买 nike

我想在按钮被选中时更改它的背景颜色,但不想使用图像。

[mBtn setBackgroundColor:[UIColor grayColor] forState:UIControlStateHighlighted];

有什么想法吗?

最佳答案

我正在回复这个旧线程,因为它在搜索此问题的解决方案时不断弹出,而我在其他地方没有看到任何解决方案。 setTintColor 仅适用于 UIButton 的突出显示状态,这确实令人讨厌。六个月前,它仅适用于 iOS 5 同样令人恼火,但希望这在未来不会成为问题。考虑到这一点,我借鉴并结合了许多社区建议,以合成一个通用解决方案,为一组处于正常状态的按钮着色。

下面的方法接受一个 NSArray 的 UIButtons 和一组颜色规范作为输入。它使用 setTintColor 将颜色规范应用于一个按钮,将结果呈现为 UIImage,并将该图像应用为整组按钮的背景图像。这避免了为按钮颜色创建离散图像文件的需要。此外,它使用可拉伸(stretch)图像来实现这一点,以便它可以处理一组不同大小的按钮(但请注意,它假定了 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]);
}

关于objective-c - 更改 StateHighlighted 上的圆形矩形按钮背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7238507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com