Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

objective c - Cocoa: NSRectFill on button click does not work

Hello I am new to Cocoa programming and I met a problem about NSRectFill.

There is one button in the window, and the following is my AppDelegate.m file:

@implementation LGAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [[NSColor redColor] set];
    NSRectFill(NSMakeRect( 50,50,10,10));
}


- (IBAction)buttonPressed:(id)sender
{
    [[NSColor greenColor] set];
    NSRectFill(NSMakeRect( 60,60,10,10));
}
@end

What I expected to see is a rectangle shows when the application starts, and another rectangle shows after clicking the button. However, only one rectangle shows, nothing happened after clicking the button. Please help me to solve this. Thank you. Yours, Z

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

well you don't have any context, the system has no idea where you want to draw. if you want to draw on a view or an image you have to use a lockFocus / unlockFocus pair.

so if you have a view as an outlet called redView

[redView lockFocus];
[[NSColor redColor] set];
NSRectFill(NSMakeRect( 50,50,10,10));
[redView unlockFocus];

but this is a really poor model, you generally want your objects to draw themselves.

when a views drawRect: method is called you already have focus and don't need the lock unlock pair


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...