3

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

L N
  • 2,856
  • 4
  • 20
  • 30

2 Answers2

2

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

meaning-matters
  • 21,929
  • 10
  • 82
  • 142
  • I ended up subclassing UIButton and implemented exactly the same way. I also setBackgroundImage for UIControlStateNormal as well. – L N Mar 06 '14 at 01:11
  • I down voted because LevinsonTechnologies should be the right answer. I've tested it and it works. That is the way it obviously was intended to be done. – Erik Engheim Nov 04 '14 at 16:53
2

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;
}
Duck
  • 34,902
  • 47
  • 248
  • 470