سؤال

I am trying to drag a CGRect, but nothing happens. The rect stays in the same place. Here is my mouseDragged: code:

-(void)mouseDragged:(NSEvent *)theEvent{

NSPoint eventLocation = [theEvent locationInWindow];
NSPoint location = [self convertPoint:eventLocation fromView:self];

int locationX = location.x;
int locationY = location.y;

[self setNeedsDisplay:TRUE];

if(CGRectContainsPoint(myRect, location)){

myRect.origin.x = locationX;
myRect.origin.y = locationY;
}
}

This code is inside of an NSView. I draw the rect myRect in drawRect:

Here is my drawRect:

- (void)drawRect:(NSRect)rect
{

int width = self.bounds.size.width;
int height = self.bounds.size.height;

myRect = CGRectMake((width/2)-50, (height /2)-50, 100, 100);


CGContextRef myContext = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(myContext, 1, 0, 0, 1);
CGContextFillRect(myContext, myRect);

 NSLog(@"drawRect: called");

}

Any ideas?

هل كانت مفيدة؟

المحلول

You're always setting myRect to a constant value inside of drawRect:. It seems like what you want is to not set myRect at all in drawRect: and to draw it with its current value. So something like this:

- (void)drawRect:(NSRect)rect
{
    CGContextRef myContext = [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor(myContext, 1, 0, 0, 1);
    CGContextFillRect(myContext, myRect);

    NSLog(@"drawRect: called");
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top