2012-10-31 28 views
1

我有一個非常簡單的項目,它涉及用drawRect繪製一個形狀,但我不相信我的drawRect函數實際上被調用。這是代碼。 (其他一切只是「單一視圖應用程序」的默認設置。)Objective C:實現drawRect

-(void)drawRect:(CGRect)aRect{ 
    NSLog(@"testing..."); 
    CGContextRef context=UIGraphicsGetCurrentContext(); 
    CGContextBeginPath(context); 
    CGContextMoveToPoint(context, 50, 50); 
    CGContextAddLineToPoint(context, 100, 120); 
    CGContextAddLineToPoint(context, 20, 100); 
    CGContextClosePath(context); 

    [[UIColor greenColor] setFill]; 
    [[UIColor redColor] setStroke]; 

    CGContextDrawPath(context,kCGPathFillStroke); 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self.view setNeedsDisplay]; 
} 

任何建議都會很棒 - 感謝您的閱讀!

+7

看起來您已將'drawRect:'放在viewcontroller類中。 Viewcontrollers不實現'drawRect:','UIView'的子類。 –

+0

是的,你只需要在'self'上調用'setNeedsDisplay'。 –

+0

好的,謝謝!仍然在學習如何做到這一點,所以將繼續留在它。 – Rogare

回答

6

看起來您已將drawRect:置於UIViewController子類中。 UIViewController的不執行drawRect:UIView的子類。

您需要創建的UIView自定義子類與實施drawRect:,然後添加到您的視圖層次無論是作爲視圖控制器的self.view prpoperty的孩子或根視圖本身。