2012-06-01 31 views
0

我可以通過將以下內容放入UIView並將其連接到故事板視圖來繪製一條線。繪製到功能的視圖

- (void)drawRect:(CGRect)rect { 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSetLineWidth(context, 5.0); 
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); 
CGFloat components[] = {0.0, 0.0, 1.0, 1.0}; 
CGColorRef color = CGColorCreate(colorspace, components); 
CGContextSetStrokeColorWithColor(context, color); 
CGContextMoveToPoint(context, 0, 0); 
CGContextAddLineToPoint(context, 10, 50); 
CGContextStrokePath(context); 
CGColorSpaceRelease(colorspace); 
CGColorRelease(color); 

}

不過,我想要做的是畫,只要按下按鈕,一條線。爲此,我假設我需要在IBAction中編寫一些代碼。我的問題是,我不能簡單地把上面的代碼放到IBAction中,因爲它給了我一個錯誤。

- (IBAction)draw:(id)sender{ 
//Place code here 

}

我的問題是,我怎麼能每按一次按鈕畫一條線?

如何連接類似的代碼來繪製一個不同的線路將被觸發,當我按下一個按鈕

回答

2

要畫上你必須繼承你的UIView

在.H

@MyCustomView : UIView { 
    } 

    @end 

在.M

@implementation MyCustomView 

- (void) drawRect: (CGRect) rect 
{ 
     CGContextRef context = UIGraphicsGetCurrentContext(); 
     CGContextSetLineWidth(context, 5.0); 
     CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); 
     CGFloat components[] = {0.0, 0.0, 1.0, 1.0}; 
     CGColorRef color = CGColorCreate(colorspace, components); 
     CGContextSetStrokeColorWithColor(context, color); 
     CGContextMoveToPoint(context, 0, 0); 
     CGContextAddLineToPoint(context, 10, 50); 
     CGContextStrokePath(context); 
     CGColorSpaceRelease(colorspace); 
     CGColorRelease(color); 
    } 

在你的ViewController

-(void)methodCallCustomView{ 

     } 

- (IBAction)draw:(id)sender{ 
    [self methodCallCustomView]; 
    } 
+0

我試過,但它沒有工作,並給出了以下錯誤: :CGContextSetLineWidth:無效的上下文0x0 – SimonRH

+0

@ user1209902我修改了我的答案,UIView的子類,並從ViewController調用您的自定義UIView – self

1

所以,你想要的的drawRect:當你按下一個按鈕來調用的方法?如果是這樣,請將消息setNeedsDisplay發送到具有drawRect:代碼的視圖。

+0

對不起一個UIView,我的描述中並不清楚。這不是我想調用的drawRect。我想調用一個包含相似但不同代碼的函數。 – SimonRH