Reputation: 11
I have this super simple example, and I'm not sure why it is not working. drawRect Never gets called. I just want a square to draw and be red. What am I doing wrong?
//Controller.h
#import <Foundation/Foundation.h>
@class CustomView;
@interface Controller : NSObject
@property (nonatomic, retain) CustomView *cv;
@end
//Controller.m
#import "Controller.h"
#import "CustomView.h"
@implementation Controller
@synthesize cv;
- (void) awakeFromNib {
NSLog(@"awakeFromNib called");
CGRect theFrame = CGRectMake(20, 20, 100, 100);
cv = [[CustomView alloc] initWithFrame:theFrame];
UIWindow *theWindow = [[UIApplication sharedApplication] keyWindow];
[theWindow addSubview:cv];
[cv setNeedsDisplay];
}
@end
//CustomView.h
#import <UIKit/UIKit.h>
@interface CustomView : UIView
@end
//CustomView.m
#import "CustomView.h"
@implementation CustomView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSLog(@"initWithFrame called");
}
return self;
}
- (void)drawRect:(CGRect)rect {
NSLog(@"drawRect called");
self.backgroundColor = [UIColor redColor];
}
@end
Upvotes: 1
Views: 4216
Reputation: 550
Rather than doing a forward reference to your CustomView class in your Controller implementation:
@class CustomView;
Trying importing the class header file:
#import "CustomView.h"
Because you require access to the API you have defined when you call:
cv = [[CustomView alloc] initWithFrame:theFrame];
A forward reference tells the compiler that there will be an implementation for the class you are using at compile time and it is best used in header files. In implementation files, I find it best to import the header.
Upvotes: 0
Reputation: 119292
You aren't drawing anything in your drawRect. You are just setting a property on the view. If you have overridden drawRect, nothing will be drawn - try calling [super drawRect:rect] (after setting your background colour) or simply draw the square yourself using:
[[UIColor redColor] set];
[[UIBezierPath bezierPathWithRect:self.bounds] fill];
EDIT:
I see your drawRect is not even being called. I'm not sure of your nib structure, but try adding cv as a subview to self.view in your controller rather than adding it to the window. Also, note that you are not retaining cv (use self.cv = rather than cv =) but this shouldn't be an issue since your view will retain it.
Upvotes: 2