Clicky

iOS Dev Nugget 85 A More Customizable Button For Different States

.

Need to run a code review on your codebase? Hire me

Sometimes you'll have a button and want to set a different background color depending on its state. Or even completely change the button's look using a custom view depending on its state. That's where CMDAwesomeButton (by @calebd) comes in.

It's a subclass of UIButton with a key method:

- (void)setValue:(id)value forKeyPath:(NSString *)keyPath state:(UIControlState)state;

So you can do something like:

CMDAwesomeButton* btn = [CMDAwesomeButton new];
[btn setValue:aColor forKeyPath:@"backgroundColor" state:UIControlStateNormal];
[btn setValue:anotherColor forKeyPath:@"backgroundColor" state:UIControlStateHighlighted];

Note that -setValue:forKeyPath:state: accepts a key path as its 2nd argument, so you can do way more sophisticated things with CMDAwesomeButton. For an example, the README for CMDAwesomeButton shows an example of how to use Sam Soffes's SAMGradientView with it to create a button with a gradient background.

CMDAwesomeButton *gradientButton = [CMDAwesomeButton new];
SAMgradientView *gradientView = [SAMGradientView new];
gradientView.backgroundColor = [UIColor clearColor];
gradientButton.backgroundView = gradientView;
[gradientButton setValue:@[
    [UIColor colorWithRed:0.145 green:0.769 blue:0.757 alpha:1.000],
    [UIColor colorWithRed:0.196 green:0.678 blue:0.800 alpha:1.000]
] forKeyPath:@"backgroundView.gradientColors" state:UIControlStateNormal];
[gradientButton setValue:@[
    [UIColor colorWithRed:0.145 green:0.769 blue:0.757 alpha:0.5],
    [UIColor colorWithRed:0.196 green:0.678 blue:0.800 alpha:0.5]
] forKeyPath:@"backgroundView.gradientColors" state:UIControlStateHighlighted];


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues