Question

I am trying to make a simple Cocoa program. I have a little black box (a subclass of NSView drawing an NSRect on screen) following my mouse around. That part I have working. What I need for it to do is: when I click the mouse I want to leave a "copy" of that black box behind.

I have been trying to get this to work for over five hours now and I have tried everything under the sun. I am sure that the solution is simple, my guess is that I am missing a grasping of the fundamental concepts.

Here is what I have (a "stay" is supposed to be the copy that stays behind):

@property NSMutableArray *stays;

...

- (void) makeStay {
    if (!_stays)
        _stays = [[NSMutableArray alloc]init];

    NSValue *newStay = [NSValue valueWithRect:self.frame];
    [_stays addObject:newStay];
}

...


-(void)drawRect:(NSRect)rect {
    [[NSColor blackColor] set];
    NSRectFill([self bounds]);

    for (int x = 0; x < _stays.count; x++) {
        NSRectFill([_stays[x] rectValue]);
    }
}

Any help on how to understand the fundamentals of NSView so that this would work would be appreciated!

Was it helpful?

Solution

From your code I'm guessing your problem is bounds.

It looks like you have an NSView which you are moving around the screen - so it's frame is its location in its superview and that is what you are saving in makeStay.

In your drawRect you fill the view's bounds - this is in view coordinates. You then try to fill the "stays", these are in superview coordinates but will be treated as view coordinates and are undoubtedly outside of the bounds of the view and so will be clipped.

Try instead having a "board" view filling your window, and your box view as a subview of that. The board view should keep and draw the list of "stays", the "box" view when clicked should add its current frame to the board views list. Those stays will always be in the bounds of the board.

HTH.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top