Search code examples
objective-cdrawibaction

How can I use an IBAction from inside my controller to draw a circle in my custom view?


I draged out a generic view and hooked it up to my circleView.m. I then dragged out a round rect button on top of that view and hooked up an IBAction to it. As of right now, when the view loads the circle is automatically drawn onto the screen. What I would like to do is draw the circle on the screen only when the button is pressed using drawRect or some other draw method. Here is my code:

drawCircleViewController.h

#import <UIKit/UIKit.h>

@interface drawCircleViewController : UIViewController

@end

drawCircleViewController.m

#import "drawCircleViewController.h"
#import "circleView.h"
@interface drawCircleViewController()
@property (nonatomic, weak) IBOutlet circleView *circleV;
@end
@implementation drawCircleViewController
@synthesize circleV = _circleV;


- (IBAction)buttonPressedToDrawCircle:(id)sender {
    // This is action I want to use to draw the circle in my circleView.m 
}

@end

circleView.h

#import <UIKit/UIKit.h>

@interface circleView : UIView

@end

circleView.m

#import "circleView.h"

@implementation circleView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


- (void)drawCircleAtPoint:(CGPoint)p
               withRadius:(CGFloat)radius 
                inContext:(CGContextRef)context
{
    UIGraphicsPushContext(context);
    CGContextBeginPath(context);
    CGContextAddArc(context, p.x, p.y, radius, 0, 2*M_PI, YES);
    CGContextStrokePath(context);
    UIGraphicsPopContext();
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGPoint midpoint;
    midpoint.x = self.bounds.origin.x + self.bounds.size.width / 2;
    midpoint.y = self.bounds.origin.y + self.bounds.size.height / 2;

#define DEFAULT_SCALE 0.90

    CGFloat size = self.bounds.size.width / 2;
    if (self.bounds.size.height < self.bounds.size.width) size = self.bounds.size.height / 2;
    size *= DEFAULT_SCALE;

    CGContextSetLineWidth(context, 5.0);
    [[UIColor blueColor] setStroke];


    [self drawCircleAtPoint:midpoint withRadius:size inContext:context];
}

@end

Solution

  • With what you have there, the simplest approach would probably be to make your circle view hidden and show it when the button is pressed.

    Otherwise, you can keep a BOOL in your view to denote whether the button has been tapped and check that during drawRect: (and use setNeedsDisplay to trigger changes).