I've currently implemented a simple selection box using mouse events and redrawing a rectangle on mouse drag. Here's my code:
-(void)drawRect:(NSRect)dirtyRect
{
if (!NSEqualRects(self.draggingBox, NSZeroRect))
{
[[NSColor grayColor] setStroke];
[[NSBezierPath bezierPathWithRect:self.draggingBox] stroke];
}
}
#pragma mark Mouse Events
- (void)mouseDown:(NSEvent *)theEvent
{
NSPoint pointInView = [self convertPoint:[theEvent locationInWindow] fromView:nil];
self.draggingBox = NSMakeRect(pointInView.x, pointInView.y, 0, 0);
[self setNeedsDisplay:YES];
}
- (void)mouseDragged:(NSEvent *)theEvent
{
NSPoint pointInView = [self convertPoint:[theEvent locationInWindow] fromView:nil];
_draggingBox.size.width = pointInView.x - (self.draggingBox.origin.x);
_draggingBox.size.height = pointInView.y - (self.draggingBox.origin.y);
[self setNeedsDisplay:YES];
}
- (void)mouseUp:(NSEvent *)theEvent
{
self.draggingBox = NSZeroRect;
[self setNeedsDisplay:YES];
}
Ref: http://cocoadev.com/HowToCreateWalkingAnts
Questions:
Is this the most efficient way to do this? If the view was complex, would it be more efficient to draw a transparent view over the main view instead of continuously redrawing the view for the duration of the mouse drag (http://www.cocoabuilder.com/archive/cocoa/99877-drawing-selection-rectangle.html)? How is this done? I can't seem to find any examples.