2012-03-28 36 views
-1

我畫出了一個通用的視圖,並將其連接到我的circleView.m。然後,我在該視圖上拖出了一個圓形的矩形按鈕,並將一個IBAction連接到它。截至目前,視圖加載時,圓形會自動繪製到屏幕上。我想要做的只是當使用drawRect或其他繪製方法按下按鈕時在屏幕上繪製圓。這裏是我的代碼:如何從我的控制器內部使用IBAction在我的自定義視圖中繪製一個圓圈?

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 
+1

也許嘗試把你用來在視圖中繪製圓的代碼(它自動繪製圓的那個)移動到IBAction方法中? – David 2012-03-28 17:23:51

回答

2

隨着你在那裏,最簡單的方法可能是讓你的圓圈視圖隱藏,並按下按鈕時顯示它。否則,您可以在視圖中保留一個BOOL來表示按鈕是否已被輕敲,並在drawRect :(並使用setNeedsDisplay觸發更改)期間檢查該按鈕。

相關問題