简体   繁体   中英

Open an NSWindow by clicking NSRect in cocoa

In my program I am able to determine whether a mouseclick was made within a certain NSRect. How can I open a new NSWindow by clicking this NSRect?

If you want to display an existing window (which you created with Interface Builder) you just call makeKeyAndOrderFront on your window object.
If you want to create a new window programmatically you find an answer here .

To handle events, you'd implement the relevant methods of NSResponder in your NSView or NSViewController subclass. For instance, you could implement mouseDown: and -mouseUp: to handle mouse clicks (in a fairly simplistic manner), like so:

- (void) mouseDown: (NSEvent *) event
{
    if ( [event type] != NSLeftMouseDown )
    {
        // not the left button, let other things handle it
        [super mouseDown: event];
        return;
    }

    NSPoint location = [self convertPoint: [event locationInWindow] fromView: nil];
    if ( !NSPointInRect(location, self.theRect) )
    {
        [super mouseDown: event];
        return;
    }

    self.hasMouseDown = YES;
}

- (void) mouseUp: (NSEvent *) event
{
    if ( (!self.hasMouseDown) || ([event type] != NSLeftMouseUp) )
    {
        [super mouseUp: event];
        return;
    }

    NSPoint location = [self convertPoint: [event locationInWindow] fromView: nil];
    if ( !NSPointInRect(location, self.theRect) )
    {
        [super mouseDown: event];
        return;
    }

    self.hasMouseDown = NO;

    // mouse went down and up within the target rect, so you can do stuff now
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM