简体   繁体   English

如何在突出显示时更改 UIButton 的背景颜色?

[英]How to change the background color of a UIButton while it's highlighted?

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?如何强制按钮改变背景颜色?

You can override UIButton 's setHighlighted method.您可以覆盖UIButtonsetHighlighted方法。

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
    }
}

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.您需要捕获两个事件, UIControlEventTouchDown 将用于当用户按下按钮时。 UIControlEventTouchUpInside and UIControlEventTouchUpOutside will be for when they release the button to return it to the normal state 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];

There is no need to override highlighted as computed property.无需覆盖highlighted为计算属性。 You can use property observer to trigger background color change:您可以使用属性观察器来触发背景颜色更改:

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
    }
}

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)
    }
}

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
        }
    }

Override highlighted variable.覆盖突出显示的变量。 Adding @IBInspectable makes you edit the highlighted backgroundColor in storyboard, which is nifty too.添加@IBInspectable使您可以在故事板中编辑突出显示的背景@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
        }
    }
}

a more compact solution (based on @aleksejs-mjaliks answer):更紧凑的解决方案(基于@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)
  }
}

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原答案: https : //stackoverflow.com/a/30604658/3659227

My best solution for Swift 3+ without subclassing.我最好的Swift 3+解决方案,无需子类化。

extension UIButton {
  func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
    let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
    UIGraphicsBeginImageContext(rect.size)
    color.setFill()
    UIRectFill(rect)
    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    setBackgroundImage(colorImage, for: state)
  }
}

With this extension it's easy to manage colors for different states and it will fade your normal color automatically in case highlighted color is not provided.使用此扩展程序可以轻松管理不同状态的颜色,如果未提供突出显示的颜色,它会自动淡化您的正常颜色。

button.setBackgroundColor(.red, for: .normal)

Here's an approach in Swift, using a UIButton extension to add an IBInspectable, called highlightedBackgroundColor.这是 Swift 中的一种方法,使用 UIButton 扩展添加一个名为 highlightBackgroundColor 的 IBInspectable。 Similar to subclassing, without requiring a subclass.类似于子类化,不需要子类。

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.我希望这有帮助。

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-

Details细节

  • Xcode 11.1 (11A1027), Swift 5 Xcode 11.1 (11A1027),Swift 5

Solution解决方案

import UIKit

extension UIColor {
    func createOnePixelImage() -> UIImage? {
        let size = CGSize(width: 1, height: 1)
        UIGraphicsBeginImageContext(size)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        context.setFillColor(cgColor)
        context.fill(CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

extension UIButton {
    func setBackground(_ color: UIColor, for state: UIControl.State) {
        setBackgroundImage(color.createOnePixelImage(), for: state)
    }
}

Usage用法

button.setBackground(.green, for: .normal)
extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        let size = CGSize(width: 1, height: 1)
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(CGRect(origin: CGPoint.zero, size: size))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(colorImage, for: forState)
    }

}

Swift 5 , thanks @Maverick Swift 5 ,感谢@Maverick

Try this !!!!试试这个 !!!!

For TouchedDown Event set One color and for TouchUpInside set the other.为 TouchedDown 事件设置一种颜色,为 TouchUpInside 设置另一种颜色。

- (IBAction)touchedDown:(id)sender {
    NSLog(@"Touched Down");
    btn1.backgroundColor=[UIColor redColor];
}

- (IBAction)touchUpInside:(id)sender {
    NSLog(@"TouchUpInside");
    btn1.backgroundColor=[UIColor whiteColor];    
}

simple is that use that UIButton Extension ONLY简单的是只使用那个 UIButton 扩展

extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        self.clipsToBounds = true  // add this to maintain corner radius
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
        }
    }

}

and use this并使用这个

 optionButton.setBackgroundColor(color: UIColor(red:0.09, green:0.42, blue:0.82, alpha:1.0), forState: .selected)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .highlighted)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .normal)

UPDATE:更新:

Use the UIButtonBackgroundColor Swift library.使用UIButtonBackgroundColor Swift 库。

OLD:老的:

Use the helpers below to create a 1 px x 1 px image with a grayscale fill color:使用下面的助手创建一个带有灰度填充颜色的 1 px x 1 px 图像:

UIImage *image = ACUTilingImageGray(248/255.0, 1);

or an RGB fill color:或 RGB 填充颜色:

UIImage *image = ACUTilingImageRGB(253/255.0, 123/255.0, 43/255.0, 1);

Then, use that image to set the button's background image:然后,使用该image设置按钮的背景图像:

[button setBackgroundImage:image forState:UIControlStateNormal];

Helpers帮手

#pragma mark - Helpers

UIImage *ACUTilingImageGray(CGFloat gray, CGFloat alpha)
{
    return ACUTilingImage(alpha, ^(CGContextRef context) {
        CGContextSetGrayFillColor(context, gray, alpha);
    });
}

UIImage *ACUTilingImageRGB(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha)
{
    return ACUTilingImage(alpha, ^(CGContextRef context) {
        CGContextSetRGBFillColor(context, red, green, blue, alpha);
    });
}

UIImage *ACUTilingImage(CGFloat alpha, void (^setFillColor)(CGContextRef context))
{
    CGRect rect = CGRectMake(0, 0, 0.5, 0.5);
    UIGraphicsBeginImageContextWithOptions(rect.size, alpha == 1, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    setFillColor(context);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Note: ACU is the class prefix of my Cocoa Touch Static Library called Acani Utilities, where AC is for Acani, and U is for Utilities.注意: ACU是我的 Cocoa Touch 静态库的类前缀,称为 Acani Utilities,其中 AC 代表 Acani,U 代表实用程序。

Subclass the UIButton and add inspectable properties for convenient use (written in Swift 3.0):子类化 UIButton 并添加可检查的属性以方便使用(用 Swift 3.0 编写):

final class SelectableBackgroundButton: UIButton {

    private struct Constants {
        static let animationDuration: NSTimeInterval = 0.1
    }

    @IBInspectable
    var animatedColorChange: Bool = true

    @IBInspectable
    var selectedBgColor: UIColor = UIColor.blackColor().colorWithAlphaComponent(0.2)

    @IBInspectable
    var normalBgColor: UIColor = UIColor.clearColor()

    override var selected: Bool {
        didSet {
            if animatedColorChange {
                UIView.animateWithDuration(Constants.animationDuration) {
                    self.backgroundColor = self.selected ? self.selectedBgColor : self.normalBgColor
                }
            } else {
                self.backgroundColor = selected ? selectedBgColor : normalBgColor
            }
        }
    }

    override var highlighted: Bool {
        didSet {
            if animatedColorChange {
                UIView.animateWithDuration(Constants.animationDuration) {
                    self.backgroundColor = self.highlighted ? self.selectedBgColor : self.normalBgColor
                }
            } else {
                self.backgroundColor = highlighted ? selectedBgColor : normalBgColor
            }
        }
    }
}

You can subclass the UIButton and make a nice forState.你可以子类化 UIButton 并创建一个很好的 forState。

colourButton.h颜色按钮.h

#import <UIKit/UIKit.h>

@interface colourButton : UIButton

-(void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state;

@end

colourButton.m颜色按钮.m

#import "colourButton.h"

@implementation colourButton
{
    NSMutableDictionary *colours;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    // If colours does not exist
    if(!colours)
    {
        colours = [NSMutableDictionary new];  // The dictionary is used to store the colour, the key is a text version of the ENUM
        colours[[NSString stringWithFormat:@"%lu", UIControlStateNormal]] = (UIColor*)self.backgroundColor;  // Store the original background colour
    }

    return self;
}

-(void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state
{
    // If it is normal then set the standard background here
    if(state & UIControlStateNormal)
    {
        [super setBackgroundColor:backgroundColor];
    }

    // Store the background colour for that state
    colours[[NSString stringWithFormat:@"%lu", state]]= backgroundColor;
}

-(void)setHighlighted:(BOOL)highlighted
{
    // Do original Highlight
    [super setHighlighted:highlighted];

    // Highlight with new colour OR replace with orignial
    if (highlighted && colours[[NSString stringWithFormat:@"%lu", UIControlStateHighlighted]])
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateHighlighted]];
    }
    else
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateNormal]];
    }
}

-(void)setSelected:(BOOL)selected
{
    // Do original Selected
    [super setSelected:selected];

    // Select with new colour OR replace with orignial
    if (selected && colours[[NSString stringWithFormat:@"%lu", UIControlStateSelected]])
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateSelected]];
    }
    else
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateNormal]];
    }
}

@end

Notes (This is an example, I know there are problems and here are some)注释(这是一个例子,我知道有问题,这里有一些)

I have used an NSMutableDictionay to store the UIColor for each State, I have to do a nasty text conversion for the Key as the UIControlState is not a nice straight Int.我使用 NSMutableDictionay 来存储每个 State 的 UIColor,我必须为 Key 做一个讨厌的文本转换,因为 UIControlState 不是一个很好的直接 Int。 If it where you could init an Array with that many objects and use the State as an index.如果你可以用那么多对象初始化一个 Array 并使用 State 作为索引。

Because of this you many have difficulties with eg a selected & disabled button, some more logic is needed.正因为如此,你们很多人在选择和禁用按钮时遇到困难,需要一些更多的逻辑。

Another problem is if you try and set multiple colours at the same time, I have not tried with a button but if you can do this it may not work另一个问题是,如果您尝试同时设置多种颜色,我还没有尝试过使用按钮,但如果您可以这样做,它可能不起作用

 [btn setBackgroundColor:colour forState:UIControlStateSelected & UIControlStateHighlighted];

I have assumed this is StoryBoard, there is no init, initWithFrame so add them if you need them.我假设这是 StoryBoard,没有 init 和 initWithFrame,所以如果需要,请添加它们。

On Storyboard... 在情节提要上...

You can change the settings for individual UIButton states. 您可以更改单个UIButton状态的设置。 For example, select "Selected" and you can then change the text color for that state. 例如,选择“选定”,然后可以更改该状态的文本颜色。

To change the background when the UIButton is highlighted: 要在突出显示UIButton时更改背景,请执行以下操作:

  1. Select the desired button in Storyboard. 在情节提要中选择所需的按钮。
  2. Select the desired state configuration. 选择所需的状态配置。 For your case, select "Highlighted." 根据您的情况,选择“突出显示”。 如何在情节提要中更改状态配置。
  3. Change the background color. 更改背景颜色。 You can now navigate to other states using Step 2 and specify the background color for that state. 现在,您可以使用第2步导航到其他状态,并指定该状态的背景色。 如何在情节提要中更改背景颜色。

Try this if you have an image:如果您有图像,请尝试此操作:

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;

or see if showsTouchWhenHighlighted is enough for you.或者看看showsTouchWhenHighlighted是否对你来说足够了。

I have open-sourced a UIButton subclass, STAButton , to fill in this gaping functionality hole.我已经开源了一个 UIButton 子类STAButton来填补这个巨大的功能漏洞。 Available under the MIT license.在 MIT 许可下可用。 Works for iOS 7+ (I have not tested with older iOS versions).适用于 iOS 7+(我没有测试过旧的 iOS 版本)。

To solve this problem I created a Category to handle backgroundColor States with UIButtons :为了解决这个问题,我创建了一个 Category 来处理带有UIButtons backgroundColor
ButtonBackgroundColor-iOS ButtonBackgroundColor-iOS

You can install the category as a pod .您可以将类别安装为pod

Easy to use with Objective-C易于使用Objective-C

@property (nonatomic, strong) UIButton *myButton;

...

[self.myButton bbc_backgroundColorNormal:[UIColor redColor]
                 backgroundColorSelected:[UIColor blueColor]];

Even more easy to use with Swift :使用Swift更容易:

import ButtonBackgroundColor

...

let myButton:UIButton = UIButton(type:.Custom)

myButton.bbc_backgroundColorNormal(UIColor.redColor(), backgroundColorSelected: UIColor.blueColor())

I recommend you import the pod with:我建议您使用以下命令导入 pod:

platform :ios, '8.0'
use_frameworks!

pod 'ButtonBackgroundColor', '~> 1.0'

Using use_frameworks!使用 use_frameworks! in your Podfile makes easier to use your pods with Swift and objective-C.在 Podfile 中使用 Swift 和 Objective-C 可以更轻松地使用 Pod。

IMPORTANT重要的

I also wrote a Blog Post with more information. 我还写了一篇包含更多信息的博客文章。

class CustomButton: UIButton {

    override var isHighlighted: Bool {
        didSet {
            if (isHighlighted) {
                alpha = 0.5
            }
            else {
                alpha = 1
            }            
        }
    }

}

Use https://github.com/swordray/UIButtonSetBackgroundColorForState使用https://github.com/swordray/UIButtonSetBackgroundColorForState

Add to Podfile using CocoaPods使用 CocoaPods 添加到 Podfile

pod "UIButtonSetBackgroundColorForState"

Swift迅速

button.setBackgroundColor(.red, forState: .highlighted)

Objective-C目标-C

[button setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];

You can easily change the highlighted/selected button background color by simply using the setBackgroundImage method on UIButton and using an image by using this UIImage(color:) initializer, like this:您只需使用 UIButton 上的setBackgroundImage方法并使用此UIImage(color:)初始化程序使用图像,即可轻松更改突出显示/选定的按钮背景颜色,如下所示:

btn.setBackgroundImage(UIImage(color: .black), for: .highlighted)

Note:笔记:

If you use the cornerRadius property for rounded borders you have to set the clipsToBounds to true so the selected background color will reserve the corner radius value.如果您对圆角边框使用cornerRadius属性,则必须将clipsToBounds设置为true ,这样所选的背景颜色将保留角半径值。

尝试tintColor

_button.tintColor = [UIColor redColor];

Here is the code in Swift to select for button state:这是 Swift 中选择按钮状态的代码:

func imageWithColor(color:UIColor) -> UIImage {
    let rect:CGRect = CGRectMake(0.0, 0.0, 1.0, 1.0)
     UIGraphicsBeginImageContext(rect.size)
    let context:CGContextRef = UIGraphicsGetCurrentContext()!
    CGContextSetFillColorWithColor(context, color.CGColor)
    CGContextFillRect(context, rect)
    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    return image;
}

Example:例子:

    self.button.setImage(self.imageWithColor(UIColor.blackColor()), forState: .Highlighted)

Drop it in and you're good to go:放下它,你就可以开始了:
*proerty can be set in IB, and if no highlighted background is set, background will not change when pressed *属性可以在IB中设置,如果没有设置高亮背景,按下时背景不会改变

private var highlightedBackgroundColors = [UIButton:UIColor]()
private var unhighlightedBackgroundColors = [UIButton:UIColor]()
extension UIButton {

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        get {
            return highlightedBackgroundColors[self]
        }

        set {
            highlightedBackgroundColors[self] = newValue
        }
    }

    override open var backgroundColor: UIColor? {
        get {
            return super.backgroundColor
        }

        set {
            unhighlightedBackgroundColors[self] = newValue
            super.backgroundColor = newValue
        }
    }

    override open var isHighlighted: Bool {
        get {
            return super.isHighlighted
        }

        set {
            if highlightedBackgroundColor != nil {
                super.backgroundColor = newValue ? highlightedBackgroundColor : unhighlightedBackgroundColors[self]
            }
            super.isHighlighted = newValue
        }
    }
}

Below UIIImage extension will generates image object with specified color parameter.UIIImage扩展下面将生成具有指定颜色参数的图像对象。

extension UIImage {
    static func imageWithColor(tintColor: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        tintColor.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
       }
    }

An example usage for a button can be applied for the button object as :按钮的示例用法可以应用于按钮对象,如下所示:

setupButton.setBackgroundImage(UIImage.imageWithColor(tintColor: UIColor(displayP3Red: 232/255, green: 130/255, blue: 121/255, alpha: 1.0)), for: UIControlState.highlighted)

setupButton.setBackgroundImage(UIImage.imageWithColor(tintColor: UIColor(displayP3Red: 255/255, green: 194/255, blue: 190/255, alpha: 1.0)), for: UIControlState.normal)

如果您不覆盖,只需设置两个操作 touchDown touchUpInside

Swift 3:斯威夫特 3:

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, forUIControlState state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color: color), for: state)
    }
}

in Swift 5在斯威夫特 5

For those who don't want to use colored background to beat the selected state对于那些不想使用彩色背景来击败选定状态的人

Simply you can beat the problem by using #Selector & if statement to change the UIButton colors for each state individually easily简单地,您可以通过使用 #Selector & if 语句轻松地单独更改每个状态的 UIButton 颜色来解决问题

For Example:例如:

    override func viewDidLoad() {
    super.viewDidLoad()
    self.myButtonOutlet.backgroundColor = UIColor.white  //to reset the button color to its original color ( optionally )
}

@IBOutlet weak var myButtonOutlet: UIButton!{
    didSet{  // Button selector and image here
        self.myButtonOutlet.setImage(UIImage(systemName: ""), for: UIControl.State.normal)

        self.myButtonOutlet.setImage(UIImage(systemName: "checkmark"), for: UIControl.State.selected)



        self.myButtonOutlet.addTarget(self, action: #selector(tappedButton), for: UIControl.Event.touchUpInside)
    }
}

@objc func tappedButton() {  // Colors selection is here
    if self.myButtonOutlet.isSelected == true {

        self.myButtonOutlet.isSelected = false
        self.myButtonOutlet.backgroundColor = UIColor.white         
    } else {
        self.myButtonOutlet.isSelected = true

        self.myButtonOutlet.backgroundColor = UIColor.black
        self.myButtonOutlet.tintColor00 = UIColor.white

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM