ios 如何在突出显示时更改 UIButton 的背景颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14523348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the background color of a UIButton while it's highlighted?
提问by MartinMoizard
At some point in my app I have a highlighted UIButton
(for example when a user has his finger on the button) and I need to change the background color while the button is highlighted (so while the finger of the user is still on the button).
在我的应用程序中的某个时刻,我有一个突出显示UIButton
(例如,当用户将手指放在按钮上时),我需要在突出显示按钮时更改背景颜色(因此当用户的手指仍在按钮上时) .
I tried the following:
我尝试了以下方法:
_button.backgroundColor = [UIColor redColor];
But it is not working. The color remains the same. I tried the same piece of code when the button is not highlighted and it works fine. I also tried calling -setNeedsDisplay
after changing the color, it didn't have any effect.
但它不起作用。颜色保持不变。当按钮没有突出显示时,我尝试了同一段代码并且它工作正常。我也尝试-setNeedsDisplay
在更改颜色后调用,它没有任何效果。
How to force the button to change the background color?
如何强制按钮改变背景颜色?
回答by Thomas Decaux
You can override UIButton
's setHighlighted
method.
您可以覆盖UIButton
的setHighlighted
方法。
Objective-C
目标-C
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backgroundColor = UIColorFromRGB(0x387038);
} else {
self.backgroundColor = UIColorFromRGB(0x5bb75b);
}
}
Swift 3.0 and Swift 4.1
Swift 3.0 和 Swift 4.1
override open var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? UIColor.black : UIColor.white
}
}
回答by Tim
Not sure if this sort of solves what you're after, or fits with your general development landscape but the first thing I would try would be to change the background colour of the button on the touchDown event.
不确定这种解决方案是否能解决您所追求的问题,或者是否适合您的总体开发环境,但我首先要尝试的是更改 touchDown 事件上按钮的背景颜色。
Option 1:
选项1:
You would need two events to be capture, UIControlEventTouchDown would be for when the user presses the button. UIControlEventTouchUpInside and UIControlEventTouchUpOutside will be for when they release the button to return it to the normal state
您需要捕获两个事件, UIControlEventTouchDown 将用于当用户按下按钮时。UIControlEventTouchUpInside 和 UIControlEventTouchUpOutside 将用于当他们释放按钮时将其返回到正常状态
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setFrame:CGRectMake(10.0f, 10.0f, 100.0f, 20.f)];
[myButton setBackgroundColor:[UIColor blueColor]];
[myButton setTitle:@"click me:" forState:UIControlStateNormal];
[myButton setTitle:@"changed" forState:UIControlStateHighlighted];
[myButton addTarget:self action:@selector(buttonHighlight:) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];
Option 2:
选项 2:
Return an image made from the highlight colour you want. This could also be a category.
返回由您想要的高亮颜色制作的图像。这也可以是一个类别。
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
and then change the highlighted state of the button:
然后更改按钮的突出显示状态:
[myButton setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forState:UIControlStateHighlighted];
回答by Aleksejs Mjaliks
There is no need to override highlighted
as computed property. You can use property observer to trigger background color change:
无需覆盖highlighted
为计算属性。您可以使用属性观察器来触发背景颜色更改:
override var highlighted: Bool {
didSet {
backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()
}
}
Swift 4
斯威夫特 4
override open var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? UIColor.lightGray : UIColor.white
}
}
回答by Giordano Scalzo
An handy generic extension in Swift:
Swift 中一个方便的通用扩展:
extension UIButton {
private func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
self.setBackgroundImage(imageWithColor(color), forState: state)
}
}
Swift 3.0
斯威夫特 3.0
extension UIButton {
private func imageWithColor(color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
self.setBackgroundImage(imageWithColor(color: color), for: state)
}
}
回答by Jake Hall
In Swift you can override the accessor of the highlighted (or selected) property rather than overriding the setHighlighted method
在 Swift 中,您可以覆盖突出显示(或选定)属性的访问器,而不是覆盖 setHighlighted 方法
override var highlighted: Bool {
get {
return super.highlighted
}
set {
if newValue {
backgroundColor = UIColor.blackColor()
}
else {
backgroundColor = UIColor.whiteColor()
}
super.highlighted = newValue
}
}
回答by mash
Override highlighted variable.
Adding @IBInspectable
makes you edit the highlighted backgroundColor in storyboard, which is nifty too.
覆盖突出显示的变量。添加@IBInspectable
使您可以在故事板中编辑突出显示的背景颜色,这也很漂亮。
class BackgroundHighlightedButton: UIButton {
@IBInspectable var highlightedBackgroundColor :UIColor?
@IBInspectable var nonHighlightedBackgroundColor :UIColor?
override var highlighted :Bool {
get {
return super.highlighted
}
set {
if newValue {
self.backgroundColor = highlightedBackgroundColor
}
else {
self.backgroundColor = nonHighlightedBackgroundColor
}
super.highlighted = newValue
}
}
}
回答by Federico Zanetello
a more compact solution (based on @aleksejs-mjaliksanswer):
更紧凑的解决方案(基于@aleksejs-mjaliks答案):
Swift 3/4+:
斯威夫特 3/4+:
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? .lightGray : .white
}
}
Swift 2:
斯威夫特 2:
override var highlighted: Bool {
didSet {
backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()
}
}
If you don't want to override, this is an updated version of @timur-bernikowich's answer (Swift 4.2):
如果您不想覆盖,这是@timur-bernikowich答案的更新版本(Swift 4.2):
extension UIButton {
func setBackgroundColor(_ color: UIColor, forState controlState: UIControl.State) {
let colorImage = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in
color.setFill()
UIBezierPath(rect: CGRect(x: 0, y: 0, width: 1, height: 1)).fill()
}
setBackgroundImage(colorImage, for: controlState)
}
}
回答by Maverick
UIButton extension with Swift 3+syntax:
带有Swift 3+语法的UIButton 扩展:
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}}
Use it like:
像这样使用它:
YourButton.setBackgroundColor(color: UIColor.white, forState: .highlighted)
Original Answer: https://stackoverflow.com/a/30604658/3659227
回答by Fostah
Here's an approach in Swift, using a UIButton extension to add an IBInspectable, called highlightedBackgroundColor. Similar to subclassing, without requiring a subclass.
这是 Swift 中的一种方法,使用 UIButton 扩展添加一个名为 highlightBackgroundColor 的 IBInspectable。类似于子类化,不需要子类。
private var HighlightedBackgroundColorKey = 0
private var NormalBackgroundColorKey = 0
extension UIButton {
@IBInspectable var highlightedBackgroundColor: UIColor? {
get {
return objc_getAssociatedObject(self, &HighlightedBackgroundColorKey) as? UIColor
}
set(newValue) {
objc_setAssociatedObject(self,
&HighlightedBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
private var normalBackgroundColor: UIColor? {
get {
return objc_getAssociatedObject(self, &NormalBackgroundColorKey) as? UIColor
}
set(newValue) {
objc_setAssociatedObject(self,
&NormalBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
override public var backgroundColor: UIColor? {
didSet {
if !highlighted {
normalBackgroundColor = backgroundColor
}
}
}
override public var highlighted: Bool {
didSet {
if let highlightedBackgroundColor = self.highlightedBackgroundColor {
if highlighted {
backgroundColor = highlightedBackgroundColor
} else {
backgroundColor = normalBackgroundColor
}
}
}
}
}
I hope this helps.
我希望这有帮助。
回答by Damien Romito
You can use this category which add the method setBackgroundColor:forState:
您可以使用添加方法setBackgroundColor:forState 的此类别:
https://github.com/damienromito/UIButton-setBackgroundColor-forState-
https://github.com/damienromito/UIButton-setBackgroundColor-forState-