使可可NSWindow半透明隐藏情节提要元素

时间:2020-05-26 14:29:42

标签: swift cocoa

在我的应用程序委托中,使用以下代码使我的窗口透明:

func applicationDidFinishLaunching(_ aNotification: Notification) {
            let visualEffect = NSVisualEffectView()
    visualEffect.translatesAutoresizingMaskIntoConstraints = false
    visualEffect.material = .dark
    visualEffect.state = .active
    visualEffect.wantsLayer = true
    visualEffect.layer?.cornerRadius = 16.0


    NSApplication.shared.mainWindow?.titleVisibility = .hidden
    NSApplication.shared.mainWindow?.styleMask.remove(.titled)
    NSApplication.shared.mainWindow?.backgroundColor = .clear
    NSApplication.shared.mainWindow?.isMovableByWindowBackground = true

    NSApplication.shared.mainWindow?.contentView?.addSubview(visualEffect)

    guard let constraints = NSApplication.shared.mainWindow?.contentView else {
      return
    }

    visualEffect.leadingAnchor.constraint(equalTo: constraints.leadingAnchor).isActive = true
    visualEffect.trailingAnchor.constraint(equalTo: constraints.trailingAnchor).isActive = true
    visualEffect.topAnchor.constraint(equalTo: constraints.topAnchor).isActive = true
    visualEffect.bottomAnchor.constraint(equalTo: constraints.bottomAnchor).isActive = true
}

问题是故事板中的每个元素都不再可见。我怎样才能解决这个问题?谢谢

1 个答案:

答案 0 :(得分:0)

您需要将所有UI作为子视图添加到NSVisualEffectView或将NSVisualEffectView移到视图层次结构的后面:

NSApplication.shared.mainWindow?.contentView?.addSubview(visualEffect, positioned: .below, relativeTo: nil)

更新: 我用Xcode创建了一个新的macOS项目,并在视图上添加了标签。然后我粘贴了您的代码,唯一更改的是上面的代码行。可以。

enter image description here