swiftmacoscocoansvisualeffectview

How to add buttons when NSVisualEffectView is used


I have created a window using NSVisualEffectView to get blur and rounded corners. Like here

The problem is I don't see my button in the window when I have NSVisualEffectView code. If I remove the code, the button is displayed. What is going wrong?

NSVisualEffectView code in AppDelegate.swift:

func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        guard let window = NSApplication.shared().windows.first else { return }
        let effect = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
        effect.blendingMode = .behindWindow
        effect.state = .active
        effect.material = .dark
        effect.wantsLayer = true
        effect.layer?.cornerRadius = 15.0
        effect.layer?.masksToBounds = true
        window.isOpaque = false
        window.backgroundColor = .clear
        window.contentView = effect
        window.titlebarAppearsTransparent = true
        window.titleVisibility = .hidden
    }

I have added some buttons in storyboard. When I run the project I don't see any buttons.

enter image description here

When I remove everything from applicationDidFinishLaunching(_ aNotification: Notification) i.e., NSVisualEffectView code, I can see the buttons.

enter image description here

Can anyone tell me what is happening?


Solution

  • I think I should have corrected you in your previous question only but I didn't.

    You are using Storyboard so why are you creating NSVisualViewEffect variable in your code?

    Search for nsvisualeffectview in the right panel(Utilities panel) where you search for buttons etc. (object library).

    enter image description here

    Drag it and resize it according to your main view controller.

    To add the blur effect and mode, go to "Attribites Inspector" in the "Utilities panel"

    enter image description here

    and set window.backgroundColor = .clear and window.isOpaque = false

    func applicationDidFinishLaunching(_ aNotification: Notification) {
            // Insert code here to initialize your application
            guard let window = NSApplication.shared.windows.first else { return }
            window.isOpaque = false
            window.backgroundColor = .clear
    }
    

    Now you can add your buttons, text fields and run the project. You can see all your added elements.

    I hope it helps!