Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make inverted color uibutton programmatically?

iOS 7 has been out there for a while now. One thing that I tried to do but unsuccessfully was to replicate the Buy button Apple built into their App Store application.

The buttons have 1 pixel borders and invert the colors when highlighted or selected.

I could make the borders but couldn't make the inverted colors effect programmatically without any images.

enter image description here enter image description here

I searched the Internet, but could not find anything useful so far.

Does anyone know how to make this kind of effect for UIButton on iOS 7?

Thanks in advance

like image 200
L N Avatar asked Aug 30 '26 10:08

L N


2 Answers

Here's what I've got:

#import <QuartzCore/QuartzCore.h>

+ (void)setCornerRadius:(CGFloat)radius ofView:(UIView*)view
{
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
}

+ (void)setBorderWidth:(CGFloat)width ofView:(UIView*)view
{
    view.layer.borderWidth = width;
}

+ (void)setBorderColor:(UIColor*)color ofView:(UIView*)view
{
    view.layer.borderColor = [color CGColor];
}

+ (void)styleButton:(UIButton*)button
{
    [Common setBorderWidth:1  ofView:button];
    [Common setCornerRadius:5 ofView:button];

    [Common setBorderColor:[UIColor blueColor] ofView:button];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];

    UIGraphicsBeginImageContextWithOptions(button.frame.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor blueColor] setFill];
    CGContextFillRect(context, CGRectMake(0, 0, button.frame.size.width, button.frame.size.height));
    UIImage*     image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [button setBackgroundImage:image forState:UIControlStateHighlighted];
}

Note that this will only work for UIButtonTypeCustom buttons.

Of course, if you use another tintColor in your app, replace [UIColor blueColor].

like image 146
meaning-matters Avatar answered Sep 04 '26 16:09

meaning-matters


You get this functionality for free in IOS when the button is in the "selected" state.

You need to create a routine for the touchUpInside Action for the button. Inside that routine you have to toggle the "selected" attribute.

- (IBAction)touchedFreeButton:(UIButton *)sender {
    self.freeButton.selected = !self.freeButton.selected;
}
like image 40
LevinsonTechnologies Avatar answered Sep 04 '26 15:09

LevinsonTechnologies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!