Put a transparent NSWindow permanently on top of another NSWindow

后端 未结 2 612
Happy的楠姐
Happy的楠姐 2020-12-05 21:15

I want to have some UI controls on top of a NSWebView and because of this problem \" https://stackoverflow.com/questions/9120868/video-in-nswebview-hides-views-

相关标签:
2条回答
  • 2020-12-05 21:47

    Swift 3 version using window controller:

    final class OverlayWindowController: NSWindowController {
      init(frame: NSRect) {
        let window = NSWindow(contentRect: frame, styleMask: .borderless, backing: .buffered, defer: false)
        super.init(window: window)
    
        window.contentViewController = MyViewController()
        window.backgroundColor = NSColor.clear
        window.isOpaque = false
      }
    
      @available(*, unavailable)
      required init?(coder: NSCoder) {
        fatalError("init(coder:) is unavailable")
      }
    }
    
    0 讨论(0)
  • 2020-12-05 22:12

    Child window is what you need.

    Create NSWindow with NSBorderlessWindowMask and define it to be transparent using - setOpaque: and - setBackgroundColor: methods. Then add newly created window as a child of window containing an instance of NSWebView (using NSWindow's - addChildWindow:ordered: method). Moving parent window will automatically cause child window to move.

    Update with working code:

    CGRect wRect = self.window.frame;
    NSView *contentView  =self.window.contentView;
    CGRect cRect = contentView.frame;
    
    CGRect rect = CGRectMake(wRect.origin.x, wRect.origin.y, cRect.size.width, cRect.size.height);
    NSWindow *overlayWindow = [[NSWindow alloc]initWithContentRect:rect 
                                                         styleMask:NSBorderlessWindowMask 
                                                           backing:NSBackingStoreBuffered 
                                                             defer:NO];
    overlayWindow.backgroundColor = [NSColor redColor];
    [overlayWindow setOpaque:NO];
    overlayWindow.alphaValue = 0.5f;
    
    [self.window addChildWindow:overlayWindow ordered:NSWindowAbove];
    
    0 讨论(0)
提交回复
热议问题