How to change the background color of a UIButton while it's highlighted?
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
}
}
UIButton background color for highlighted/selected state issue
I found the issue, UIButton
was set to System.I simply changed it to Custom, it started working as expected.
How do I set UIButton background color forState: UIControlState.Highlighted in Swift
If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:
for Swift 3
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, forState: forState)
}
}
for Swift 4
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)
}
}
}
You use it just like setBackgroundImage
:
yourButton.setBackgroundColor(color: UIColor.white, forState: UIControl.State.highlighted)
How to change the highlighted color of a UIButton?
Try to Override the UIButton with the following Method.. and just change the backgroud color of button when its in highlighted state.
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backgroundColor = [UIColor Your Customcolor];
}
else{
self.backgroundColor = [UIColor Your DefaultColor];
}
}
Try it..hope it helps
Change background color of UIButton when Highlighted
Changing the internal layer hierarchy of a UIButton is not recommended since it may break in a future update of the iOS. Also, it may cause Apple to reject your application. A better solution would be to create a button subclass. Here is an example of how to do it:
@interface MyButton : UIButton
@end
@implementation MyButton
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self addObserver:self forKeyPath:@"highlighted" options:NSKeyValueObservingOptionNew context:NULL];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
if (self.highlighted == YES)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
const CGFloat *topGradientColorComponents = CGColorGetComponents([UIColor whiteColor].CGColor);
const CGFloat *bottomGradientColorComponents = CGColorGetComponents([UIColor blackColor].CGColor);
CGFloat colors[] =
{
topGradientColorComponents[0], topGradientColorComponents[1], topGradientColorComponents[2], topGradientColorComponents[3],
bottomGradientColorComponents[0], bottomGradientColorComponents[1], bottomGradientColorComponents[2], bottomGradientColorComponents[3]
};
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors) / (sizeof(colors[0]) * 4));
CGColorSpaceRelease(rgb);
CGContextDrawLinearGradient(ctx, gradient, CGPointMake(0, 0), CGPointMake(0, self.bounds.size.height), 0);
CGGradientRelease(gradient);
}
else
{
// Do custom drawing for normal state
}
}
- (void)dealloc
{
[self removeObserver:self forKeyPath:@"highlighted"];
[super dealloc];
}
@end
You may need to modify it a bit to get it to do what you want but I think you get the basic idea.
How to set UIButton background color by state
Get an UIImage
from UIColor
, use that image as background image for the button.
- (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;
}
[button setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateNormal];
[button setBackgroundImage:[self imageWithColor:[UIColor redColor]] forState:UIControlStateHighlighted];
ObjectiveC - UIButton remains highlighted/selected and background color and font color changes when highlighted/selected
I was able to achieve the function you are working on and below is how i did it.
I created the design via storyboard and connected all the 9 button's actions methods to a single Selector method, inside the action method with the help sender parameter we can get the selected buttons reference and use it.
- (IBAction)btnPressed:(UIButton*)sender {
/* Below for loop works as a reset for setting the default colour of button and to not select the same one twice*/
for (UIButton* button in buttons) {
[button setSelected:NO];
[button setBackgroundColor:[UIColor whiteColor]];
[button setUserInteractionEnabled:true];
// [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
}
NSInteger tag = sender.tag; // Here we get the sender tag, which we can use for our needs. Also we can directly use the sender and get the title or whatsoever needed.
/*Now below line works as a toggle for the button where multiple buttons can't be selected at the same time.*/
sender.selected = ! sender.selected;
if(sender.selected)
{
/* Here we set the color for the button and handle the selected function*/
[sender setSelected:YES];
[sender setUserInteractionEnabled:false];
[sender setBackgroundColor:[UIColor magentaColor]];
}
}
You can also add custom layer for the button by using the "sender.Layer" property.
The Whole code is added below,
All the button's action needs to be connected to a single selector method,
- (IBAction)btnPressed:(UIButton*)sender;
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *mainViewOL;
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@property (weak, nonatomic) IBOutlet UIButton *btn3;
@property (weak, nonatomic) IBOutlet UIButton *btn4;
@property (weak, nonatomic) IBOutlet UIButton *btn5;
@property (weak, nonatomic) IBOutlet UIButton *btn6;
@property (weak, nonatomic) IBOutlet UIButton *btn7;
@property (weak, nonatomic) IBOutlet UIButton *btn8;
@property (weak, nonatomic) IBOutlet UIButton *btn9;
@end
@implementation ViewController
NSArray* buttons;
- (void)viewDidLoad {
[super viewDidLoad];
buttons = [NSArray arrayWithObjects:_btn1, _btn2, _btn3,_btn4,_btn5,_btn6,_btn7,_btn8,_btn9,nil];
self.mainViewOL.layer.shadowRadius = 5;
self.mainViewOL.layer.shadowColor = [UIColor colorWithRed:211.f/255.f green:211.f/255.f blue:211.f/255.f alpha:1.f].CGColor;
self.mainViewOL.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
self.mainViewOL.layer.shadowOpacity = 0.9f;
self.mainViewOL.layer.masksToBounds = NO;
/* I Have added the 9 button's in an array and used it to reduce the lines of code and for easy understanding as well*/
for (UIButton* button in buttons) {
button.layer.borderColor = [UIColor lightGrayColor].CGColor;
button.layer.borderWidth =1.0f;
}
}
- (IBAction)btnPressed:(UIButton*)sender {
for (UIButton* button in buttons) {
[button setSelected:NO];
[button setBackgroundColor:[UIColor whiteColor]];
[button setUserInteractionEnabled:true];
// [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; //Based on your needs and colour variant you cant add properties to the button for different control states.
[button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
}
NSInteger tag = sender.tag;
sender.selected = ! sender.selected;
if(sender.selected)
{
[sender setSelected:YES];
[sender setUserInteractionEnabled:false];
[sender setBackgroundColor:[UIColor purpleColor]];
sender.backgroundColor = [UIColor magentaColor];
}
}
@end
And the Final Result
Ignore the delay in button selection, it is caused by the video to gif conversion.
Hope This helps.
Related Topics
How to Adjust Font Size to Fit Height and Width of Uilabel
How to Increment the Filename If File Already Exists
Disabling Auto-Play in Full Screen on Ios
Updating Configuration Profile Installed in iOS Device in Mdm
Ios Simple Tcp Connection Example
Programmatically Get Own Phone Number in Ios
How to Do Base64 Encoding on Ios
Looking to Understand the iOS Uiviewcontroller Lifecycle
How to Link to Apps on the App Store
How to Animate Constraint Changes
How to Make a Uitextfield Move Up When the Keyboard Is Present - on Starting to Edit
How to Create Delegates in Objective-C
How to Develop or Migrate Apps For Iphone 5 Screen Resolution
How to Develop For Iphone Using a Windows Development Machine
How to Download Files Using Axios
Dateformatter'S Returns Nil For Specific Date Strings Without Time in Swift