I needed a gradient button that didn’t suck, that I could add a shadow and a corner radius to. This was my solution. It’s awesome. USE IT! What! Yeah! Enjoy!
The header -
1 2 3 4 5 6 7 8 9 10 | #import <UIKit/UIKit.h> @interface GradientButton : UIButton @property (nonatomic, strong) UIColor *highColor; @property (nonatomic, strong) UIColor *lowColor; @property (nonatomic, strong) CALayer *wrapperLayer; @property (nonatomic, strong) CAGradientLayer *gradientLayer; @end |
The implementation -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | #import "GradientButton.h" @interface GradientButton () - (UIColor *)darkerColorForColor:(UIColor *)color; @end @implementation GradientButton - (id)initWithFrame:(CGRect)frame withHighColor:(UIColor *)firstColor andLowColor:(UIColor *)secondColor { self = [super initWithFrame:frame]; if (self) { [self setHighColor:firstColor]; [self setLowColor:secondColor]; } return self; } - (void) awakeFromNib { [self setupGradient]; } -(void)drawRect:(CGRect)rect { [self setupGradient]; } -(void)setupGradient { [self setClipsToBounds:NO]; if (!_gradientLayer) { _gradientLayer = [CAGradientLayer layer]; [_gradientLayer setFrame:[self bounds]]; [_gradientLayer setColors:@[(id)[_highColor CGColor], (id)[_lowColor CGColor]]]; _wrapperLayer = [CALayer layer]; [_wrapperLayer setFrame:[self bounds]]; [_wrapperLayer setCornerRadius:5.0f]; [_wrapperLayer setMasksToBounds:YES]; [_wrapperLayer setBorderColor:[[UIColor darkGrayColor] CGColor]]; [_wrapperLayer setBorderWidth:1.0f]; [_wrapperLayer addSublayer:_gradientLayer]; [[self layer] insertSublayer:_wrapperLayer atIndex:0]; } else { if (self.highlighted) { return; } [_gradientLayer setColors:@[(id)[_highColor CGColor], (id)[_lowColor CGColor]]]; } [[self layer] setShadowColor:[[UIColor blackColor] CGColor]]; [[self layer] setShadowOffset:CGSizeMake(2, 2)]; [[self layer] setShadowOpacity:0.8f]; [[self layer] setShadowRadius:5.0f]; [[self layer] setShadowPath:[[UIBezierPath bezierPathWithRoundedRect:[self bounds] cornerRadius:5.0f] CGPath]]; } -(void)setHighlighted:(BOOL)highlighted { if (highlighted != self.highlighted){ UIColor *darkColor = [self darkerColorForColor:_highColor]; UIColor *lowColor = [self darkerColorForColor:_lowColor]; [_gradientLayer setColors:@[(id)[darkColor CGColor], (id)[lowColor CGColor]]]; [[self layer] replaceSublayer:_gradientLayer with:_gradientLayer]; } [self setNeedsDisplay]; [super setHighlighted:highlighted]; } - (UIColor *)darkerColorForColor:(UIColor *)color { float red, green, blue, alpha; if ([color getRed:&red green:&green blue:&blue alpha:&alpha]) { return [UIColor colorWithRed:MAX(red - 0.2, 0.0) green:MAX(green - 0.2, 0.0) blue:MAX(blue - 0.2, 0.0) alpha:alpha]; } return nil; } @end |




