views:

153

answers:

4

I have some custom drawing code in drawRect which also performs some calculation of sizes.

When is the earliest I can be sure that this code has been loaded, e.g. if I want to modify it's containers size accordingly?

A: 

Just before the view is displayed or when you call

[aView setNeedsDisplay];
Tom Irving
But is there any callback at this stage?
Egil
No, you're going to have to put something in the drawRect method yourself for that.
Tom Irving
+2  A: 

-[NSView viewWillDraw] is a reasonable place for last minute layout.

Ken
this exists on iphone?
Egil
I think he means viewWillAppear - and it happens every time the view appears. viewWillDisappear is the corresponding exit function.
Adam Eberbach
But wouldn't 'willAppear' be called before 'draw'?
Egil
`viewWillAppear` and `viewWillAppear` are only called on `UIViewController` s. If your view isn't managed by a view controller you won't get these methods.
Jasarien
Sorry, I meant what I said, but hadn't noticed that this was for iPhone.
Ken
Also, yes, sounds like `viewWillAppear` might be a good place for this. We're suggesting you move your code _out_ of drawRect. You really should do your layout prior to drawing.
Ken
The work requires the graphics context so I don't see how this can be done before draw is called.
Egil
+1  A: 

I have some custom drawing code in drawRect which also performs some calculation of sizes.

When is the earliest I can be sure that this code has been loaded, e.g. if I want to modify it's containers size accordingly?

An object can't exist until its class is fully loaded. If you have an instance, the class that it's an instance of is completely loaded, because you wouldn't have an instance of it if it wasn't.

As for when it's called: It's called when you need to draw. This normally happens as part of the event loop, if anything has marked the view as needing display. It is possible to directly tell an NSView to display, but, as far as I can tell, this is not possible for UIViews.

So, if you need to do something to it before it gets told to, either do it immediately after creating it or, if you're about to set the view as needing display, do it before you do that.

Peter Hosey
A: 

I just created my first customView app. This was one of my questions. my drawRect method was called once upon creating my window (or recreating). And millions of time when resizing my window.

RW