praveena
praveena

Reputation: 723

How to draw a simple line without using Interface Builder?

I'm a beginner. I just want to draw a simple line without using IB . code I used is

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);
}

But I'm not able to draw. Can you please help me. Thanks in advance.

Upvotes: 0

Views: 1682

Answers (1)

John Lemberger
John Lemberger

Reputation: 2699

The code in viewWillAppear doesn't do anything because line is never added to the view hierarchy. MyView drawRect is never called because of the above and "myView" is allocated as a UIView instead of a MyView. Try changing the alloc in the view controller init.

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

Also the code will leak as written. Look into retain & release memory management.

Upvotes: 1

Related Questions