Ios – Create circle button in iOS7 without images

iosios7uibutton

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?

Best Answer

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

Related Topic