Can't Add Subview!?!

Discussion in 'iOS Programming' started by Blakeasd, Jan 5, 2013.

  1. Blakeasd, Jan 5, 2013
    Last edited: Jan 5, 2013

    Blakeasd macrumors 6502a

    Dec 29, 2009

    I am new to iPhone programming, but I have done Mac programming since around 2009. I created a new "Single View" project in Xcode for the iPhone and I am attempting (without success) to add a subview. I created a subclass of UIView and called it "DrawingView". This is my DrawingView.m code:

    #import "DrawingView.h"
    @implementation DrawingView
    - (id)initWithFrame:(CGRect)frame
        self = [super initWithFrame:frame];
        if (self) {
            [self setOpaque:YES];
        return self;
    - (void)drawRect:(CGRect)rect
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
        CGContextFillRect(context, self.frame);
    The goal was to have this view be red. In the standard view controller (the Xcode generated one) I add a field:

    DrawingView *drawingView;
    In the viewDidLoad: of the View controller I added this code (after [super viewDidLoad]):

       CGRect screenBounds;
        screenBounds = [[UIScreen mainScreen] bounds];
        [drawingView initWithFrame:screenBounds];
        [self.view addSubview:drawingView];
    When I run my app I get the standard gray screen :mad: ! Why does this code not yield a red screen?:confused:

  2. ArtOfWarfare macrumors G3


    Nov 26, 2007
    You never allocated memory for your DrawingView.

    Somewhere in your code you should have something like:

    drawingView = [[DrawingView  alloc] initWithFrame:screenBounds];
  3. Blakeasd thread starter macrumors 6502a

    Dec 29, 2009

Share This Page