旧版本的 Swift/Xcode 似乎有很多关于此的问题,但由于某种原因,它无法与最新的更新一起使用。我创建了一个 NSVisualEffectView、blurryView,并将子视图添加到我的主视图中:
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.
}
...
}
但是当我运行它时,对窗口没有任何影响。 (当我将其设置为窗口内并将其分层在其他视图之上时,模糊效果正常,但我只希望窗口模糊。)我也尝试在我的 App Delegate 类中执行相同的操作,但我可以无法将我的窗口连接为插座,因此无法将模糊视图添加到窗口。代码如下:
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)
}
...
}
斯威夫特 5: 只需将其添加到您的 viewWillAppear 中,它就应该可以工作:
override func viewWillAppear() {
super.viewWillAppear()
// Adds transparency to the app
view.window?.isOpaque = false
view.window?.alphaValue = 0.98 // you can remove this line but it adds a nice effect to it
let blurView = NSVisualEffectView(frame: view.bounds)
blurView.blendingMode = .behindWindow
blurView.material = .fullScreenUI
blurView.state = .active
view.window?.contentView?.addSubview(blurView)
}