Objective c 如何在不使用Interface Builder的情况下绘制简单的直线?

Objective c 如何在不使用Interface Builder的情况下绘制简单的直线?,objective-c,ios4,Objective C,Ios4,我是初学者。我只想画一条简单的线,不用IB。 我使用的代码是 lineViewController.m -(id)init { if(self = [super init]) { myView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,440)]; myView.backgroundColor = [UIColor grayColor]; mView = [[UIView a

我是初学者。我只想画一条简单的线,不用IB。 我使用的代码是

lineViewController.m

-(id)init
{
    if(self = [super init])
    {
        myView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,440)];
        myView.backgroundColor = [UIColor grayColor];
        mView = [[UIView alloc]initWithFrame:CGRectMake(0,0,200,200)];

        self.view = myView;
        [myView addSubView:mView];          
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    line = [[MyView alloc]init];
    [line setNeedsDisplay];         
}
MyView.m

#import "MyView.h"

@implementation MyView

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, red);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, 150.0f, 200.0f);
    CGContextSetLineWidth(c, 5.0f);
    CGContextAddLineToPoint(c, 50,300);
    CGContextAddLineToPoint(c, 260,300);
    CGContextClosePath(c);
}
但我不会画画。你能帮帮我吗。
提前感谢。

视图中的代码不会显示任何功能,因为该行从未添加到视图层次结构中。由于上述原因,从未调用MyView drawRect,“MyView”被分配为UIView而不是MyView。尝试在视图控制器初始化中更改alloc

myView = [[MyView alloc]initWithFrame:CGRectMake(0,0,320,440)];

代码也会像写的那样泄漏。查看保留和释放内存管理。

首先,您忘记了
CGContextRef c=UIGraphicsGetCurrentContext()对不起,我忘了在这里输入。但是我把它放在了我的代码中。