2012-10-31 23 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的孩子或根视图本身。