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

uibutton background color not changing swift
uibutton change background color when pressed swift
uibutton background color swift
swift change button color when pressed
uibutton set selected state programmatically
swift change background color programmatically
uibutton highlight color
uibutton selected and unselected swift

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

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.

How to force the button to change the background color?

You can override UIButton's setHighlighted method.

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

override open var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.black : UIColor.white
    }
}

Extending UIButton in Swift with Background Color for State, For instance, you can change the title, font, text color, shadow color, image, and background image, but not the background color. For some  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). I tried the following: _button.backgroundColor = [UIColor redColor]; But it is not working.

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.

Option 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

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:

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];

How to change a button background color using Swift?, To change the background color of a button in iOS application we need to access the property ' backgroundColor' of the UIButton. We can do this in two ways, programmatically and using the storyboard. Swift Tool Belt, Part 8: Extending UIButton with Background Color for State The eighth item in my Swift Tool Belt is an extension for UIButton . This extension adds a bit of functionality that is sorely missing from UIButton , giving you the ability to set the background color for different button states.

There is no need to override highlighted as computed property. You can use property observer to trigger background color change:

override var highlighted: Bool {
    didSet {
        backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()
    }
}

Swift 4

override open var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.lightGray : UIColor.white
    }
}

Highlight a button when Pressed In swift, How do I change the color of a button in Swift? Is there any way to change the background of a uibutton while it is highlighted and then have it revert back to original state?

An handy generic extension in 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

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

Changing UIButton background color based on state and the color , Now the switch to selected happens smoothly but when the button swaps back to normal, the background color change lags to the point where it is noticeably late. Now I change the 'state config' to 'Default', the 'background' to 'blackPixel' (or whatever) and the 'Text Color' to 'white color'. I guess you can use these pixels whenever you need to apply a colour when you only have access to images in the Storyboard editor.

In Swift you can override the accessor of the highlighted (or selected) property rather than overriding the setHighlighted method

override var highlighted: Bool {
        get {
            return super.highlighted
        }
        set {
            if newValue {
                backgroundColor = UIColor.blackColor()
            }
            else {
                backgroundColor = UIColor.whiteColor()
            }
            super.highlighted = newValue
        }
    }

Setting UIButton background color · ClassyKit/Classy Wiki · GitHub, We want to be able to set the background color by simply setting a UIColor property and a control state. To do this, we start with the following  uibutton selected color (18) 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).

Can't change background color UIButton |Apple Developer Forums, Hi there guys. I'm trying to change the background color on a custom UIButton class. The button is in the storyboard and i've assigned the  It seems to be possible to change the background color of the system UIButton, but it remains white in the focused state. I can switch the button to custom but I then lose the shadows etc. for the focused state, is there a way to reenable them with a custom button.

UIButton+BackgroundColor on CocoaPods.org, A category or extension for UIButton to set solid background color as background image. Installation. Usage. Import <UIButton+BackgroundColor.h> , then you  The ambiguous warning likely comes from the fact that your sender is of type 'id'. Change that to UIButton, or cast it to a UIButton, to remove the warning. Best way to do this is to add an action on TouchDownInside to change the background color, then for TouchUpInside and TouchUpOutside actions you set it back to normal background color.

backgroundColor on UIButton for different touch states – Something , In iOS we can change the colour in the background in two ways. The first from UIView and Apple decided to do dot extended it for the UIButton. Set the line spacing, margins, or background color: Line Spacing - Select the amount of space to appear above and below each line. Margins - Select the amount of space to appear on the left and right sides of each page. Choose Narrow, Normal, or Wide margins. Color Mode - Select the color scheme

Comments
  • Check this post somethingaboutios.wordpress.com/2016/02/09/… and this pod github.com/GabrielMassana/ButtonBackgroundColor-iOS
  • Yeah. It is kind of nice way to do this. Because you can define several similar buttons.
  • Just a newbie question, where would you subclass that button method? If I have a button in a view controller named ConversionViewController, how would I setup the button to change the background color when highlighted or tapped? Would I subclass the setHIghlighted in the COnversionViewController?
  • So there is one problem with this answer that I found. If you want to have the same color be available when you select theButton then setHighlighted gets called after setSelected and thus will override any selected styling you have. The solution above might be better if you want to select the button as well
  • @YakivKovalskiy assuming you're using a sub-class, you could add two UIColor properties e.g. normalBackground and highlightedBackground, then assign self.backgroundColor = normalBackground or highlightedBackground accordingly. Don't forget to add an init method for ease of use e.g. initWithBackground:highlightedBackground:
  • Nice solution, just one suggestion: backgroundColor = isHighlighted ? .lightGray : .white
  • Add UIControlEventTouchUpOutside and UIControlEventTouchCancel to buttonHighlight: event list and it will work always.
  • Option two is the best that I have found so far. I guess, however, that storyboards do have their advantages in this case!
  • Answer by Thomas is better and that's what I use also
  • If you're using layer.cornerRadius and go with option #2, you'll need to make sure to set clipsToBounds to true to get the image's corners rounded as well.
  • If someone stops by and needs an answer in Swift: stackoverflow.com/questions/26600980/…