Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...