Update NSView in function of events
I have a main view (subclass of NSView) and as i'm new to cocoa, i'd like to know how to update the view in function of events.
I know there are many methods that take events such as -(void)mouseMoved:(NSEvent*)event
or - (void)mouseClicked:(NSEvent*)event
My algorithm to determine what t开发者_开发技巧o do is ready. I want to know where I should update the main view: is it in the -(void)mouseMoved:(NSEvent*)event
or in the - (void)drawRect:(NSRect)dirtyRect
. And if it is in drawRect, then how should i pass the information to it?
Thanks in advance!
Here's a quick explanation that will hopefully get you on your way:
- Handle events
User actions are communicated to your views and windows by events (keyboard + mouse) and actions (events interpreted by buttons and other controls). Your views should react to these events and actions by updating the model, which are the lower-level data structures that represent whatever your program displays to the user. If Cocoa, the view typically communicates through a controller object to make changes to the model.
- Invalidate display / trigger redraw
After you have updated your model, you need to inform the view that it needs to redraw. This can be done in several ways, but the simplest way to do it is -setNeedsDisplay:YES
. This will ensure that at some point in the immediate future, your view will redraw itself to display the updated model data.
- Draw
At some point Cocoa will call -drawRect:
on your view. Inside -drawRect:
, you should read the requisite data from your model and draw the necessary graphics. You shouldn't do any manipulation of the model in this method.
精彩评论