I would like to recreate the circular buttons found in the Clock app in iOS7. The buttons are basically circles with different appearance depending on the button states (green border, red border, grey fill).
I could of course achieve this using a simple UIButton with images for the different states.
However I am looking for a solution which draws the circle programmatically, so I can easily change radius, stroke width, etc.
As far as I can see UIButton only allows me to define an UIImage for each state, so I cannot modify the layers per state directly (e.g. provide a layer with cornerRadius). Is there another way?
Creating a custom button may be helpful.
in the .h file;
#import <UIKit/UIKit.h>
@interface CircleLineButton : UIButton
- (void)drawCircleButton:(UIColor *)color;
@end
in the .m file;
#import "CircleLineButton.h"
@interface CircleLineButton ()
@property (nonatomic, strong) CAShapeLayer *circleLayer;
@property (nonatomic, strong) UIColor *color;
@end
@implementation CircleLineButton
- (void)drawCircleButton:(UIColor *)color
{
self.color = color;
[self setTitleColor:color forState:UIControlStateNormal];
self.circleLayer = [CAShapeLayer layer];
[self.circleLayer setBounds:CGRectMake(0.0f, 0.0f, [self bounds].size.width,
[self bounds].size.height)];
[self.circleLayer setPosition:CGPointMake(CGRectGetMidX([self bounds]),CGRectGetMidY([self bounds]))];
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
[self.circleLayer setPath:[path CGPath]];
[self.circleLayer setStrokeColor:[color CGColor]];
[self.circleLayer setLineWidth:2.0f];
[self.circleLayer setFillColor:[[UIColor clearColor] CGColor]];
[[self layer] addSublayer:self.circleLayer];
}
- (void)setHighlighted:(BOOL)highlighted
{
if (highlighted)
{
self.titleLabel.textColor = [UIColor whiteColor];
[self.circleLayer setFillColor:self.color.CGColor];
}
else
{
[self.circleLayer setFillColor:[UIColor clearColor].CGColor];
self.titleLabel.textColor = self.color;
}
}
@end
And in the view controller, call [self.myCircleButton drawCircleButton:[UIColor myColor]]
There are lot of ways you could accomplish this, for example:
Use CAShapedLayer
Subclass UIView and use the drawRect: method to draw a circle
Just have a square UIView and use the layer.cornerRadius property.
Depending on your needs, something as simple as creating normal UIButton and calling
myButton.layer.cornerRadius = myButton.bounds.size.width / 2.0;
could work (you'll need to include the Quartz Framework)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With