首页 > 解决方案 > 如何有一个投射在 NSView 之外的按钮?

问题描述

我想实现一个投射在 NSView 之外的按钮。类似的按钮如下图所示。

标签: objective-cmacoscocoansviewnsbutton

解决方案


如果您必须让视图溢出窗口,则无法使用masksToBound. CALayer您需要使用子无边框窗口并正确定位它。

这是一个示例(在 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];
}

此屏幕截图中的红色圆圈是子窗口。

溢出的子窗口


推荐阅读