How can I use NSVisualEffectView to blend window w

2019-05-14 07:19发布

There seem to be a bunch of questions on this for old versions of Swift/Xcode, but for some reason it hasn't been working with the latest update. I created a NSVisualEffectView, blurryView, and added the subview to my main view:

class ViewController: NSViewController {
    @IBOutlet weak var blurryView: NSVisualEffectView! 
    override func viewDidLoad() {
        super.viewDidLoad()

        //background styling
        blurryView.wantsLayer = true
        blurryView.blendingMode = NSVisualEffectBlendingMode.behindWindow
        blurryView.material = NSVisualEffectMaterial.dark
        blurryView.state = NSVisualEffectState.active

        self.view.addSubview(blurryView, positioned: NSWindowOrderingMode.above, relativeTo: nil)

        // Do any additional setup after loading the view.
    }
...
}

But when I run it, there is no effect on the window. (when I set it to within window, and layer it on top of my other view, the blur works correctly, but I only want the window to blur.) I also tried doing the same thing in my App Delegate class, but I can't connect my window as an outlet, and therefore can't add the blurry view to the window. Here's what the code would look like:

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application

        blurryView.wantsLayer = true
        blurryView.blendingMode = NSVisualEffectBlendingMode.withinWindow
        blurryView.material = NSVisualEffectMaterial.dark
        blurryView.state = NSVisualEffectState.active

        self.window.contentView?.addSubview(blurryView)

    }
...
}

To get an idea if what I'm looking for: NSVisualEffectView Vibrancy

1条回答
干净又极端
2楼-- · 2019-05-14 08:00

It works quite easy:

  1. In Interface Builder drag a NSVisualEffectView directly as a subview of the main view of your scene.
  2. In the Properties Inspector set Blending Mode to Behind Window
  3. Add the rest of the views you need as subviews of the NSVisualEffectView
  4. That's it, you're done

Here's an example:

enter image description here

Panel 1 View Controller is my blurred view, Background View is the first (non-blurred) view in my "real"view hierarchy.

查看更多
登录 后发表回答