我拖出一个通用视图,并将其连接到我的circleView.m。然后,我在该视图顶部拖出一个圆形矩形按钮,并将一个IBAction连接到它。截至目前,当视图加载时,圆圈会自动绘制到屏幕上。我想做的是,只有当使用drawRect或其他绘制方法按下按钮时,才能在屏幕上绘制圆圈。这是我的代码:
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
有了这些,最简单的方法可能是隐藏圆形视图,并在按下按钮时显示它。
否则,您可以在视图中保留BOOL,以表示按钮是否已被点击,并在drawRect:(并使用setNeedsDisplay触发更改)期间进行检查。