objective-cmacoscocoansviewnsbutton

How to have a button which is projected outside the NSView?


I want to implement a button which is projected outside the NSView. The similar button is shown in below image.


Solution

  • If you have to have a view overflowing the window, you can't do that using the masksToBound property of CALayer. You need to use a child borderless window and position it correctly.

    Here's an example (in ObjC):

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        // Insert code here to initialize your application
    
    
        NSRect windowFrame = self.window.frame;
        NSRect childWindowFrame = {
            .origin.x = CGRectGetMidX(windowFrame) - 25,
            .origin.y = CGRectGetMinY(windowFrame) - 25,
            .size.width = 50,
            .size.height = 50,
        };
    
        NSWindow *childWindow = [[NSWindow alloc] initWithContentRect:childWindowFrame
                                                            styleMask:NSWindowStyleMaskBorderless
                                                              backing:NSBackingStoreBuffered
                                                                defer:YES];
        childWindow.backgroundColor = [NSColor clearColor];
        childWindow.contentView.wantsLayer = YES;
        childWindow.contentView.layer.backgroundColor = [NSColor redColor].CGColor;
        childWindow.contentView.layer.cornerRadius = 25.0;
    
    
    
        [self.window addChildWindow:childWindow ordered:NSWindowAbove];
    }
    

    The red circle in this screenshot is the child window.

    overflowing child window