Reputation: 17573
I have created a UIView subclass in order to implement a custom drawRect method. By putting some logs in the code I found that drawRect is actually getting called twice as the view first gets set up by its view controller. Why is this?
The other issue is that my UIView subclass has an ivar named needsToDrawTools. My designated initializer for this subclass sets the value of needsToDrawTools to YES. The drawRect method then checks this value. If YES, it draws the tools and then sets the value of needsToDrawTools to NO so that it never re-draws the tools.
BUT, somehow the value of needsToDrawTools is NO by the time drawRect is called. Nowhere in my code am I setting it to NO, other than from within the if(needsToDrawTools) statement inside drawRect. But since needsToDrawTools is already NO by the time it reaches that if statement, the code inside the statement never even runs. If I remove that IF statement altogether, then it does run of course and I see what I expect in the view. But I don't want to remove the IF statement because that will result in re-drawing of things that don't need to be re-drawn.
Here's my code:
- (id)initWithParentViewController:(NewPhotoEditingViewController *)vc
{
self = [super init];
if (self) {
parentVC = vc;
needsToDrawTools = YES;
NSLog(@"needsToDrawTools: %i",needsToDrawTools); //Console result: 1
}
return self;
}
#pragma mark - Drawing
- (void)drawRect:(CGRect)rect
{
NSLog(@"needsToDrawTools: %i",needsToDrawTools); //Console result: 0 !!!!!
if (needsToDrawTools){
NSLog(@"drawingTools"); //Never shows up in the console
UIBezierPath *toolPointDragger = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(75, 100, 30, 30)];
[[UIColor blackColor] setStroke];
toolPointDragger.lineWidth = 6;
[toolPointDragger stroke];
[[UIColor blueColor] setFill];
[toolPointDragger fill];
needsToDrawTools = NO;
}
}
So again, my two questions are:
Why is drawRect being called twice? I assume it gets called the first time automatically as part of the view loading process, but I don't know why it then gets called again.
How does needsToDrawTools end up with a value of NO?
Upvotes: 1
Views: 2139
Reputation: 125037
It sounds like you've got more than one instance of this view. Perhaps you're creating one programmatically and loading one from a nib? Objective-C will set all ivars to zero (or nil, or NO) when an object is created, and if you're loading an instance of your view from a nib, it won't be initialized with your -(id)initWithParentViewController:
and needsToDrawTools
should be NO for that view.
Upvotes: 3