Skip to content

Instantly share code, notes, and snippets.

@alexandersandberg
Created October 20, 2022 16:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandersandberg/91bc09deb3b8d2d59b445301648fbdfe to your computer and use it in GitHub Desktop.
Save alexandersandberg/91bc09deb3b8d2d59b445301648fbdfe to your computer and use it in GitHub Desktop.
//
// TranslucentTitleBarApp.swift
// TranslucentTitleBar
//
// Created by Alexander Sandberg on 20.10.22.
//
import SwiftUI
@main
struct TranslucentTitleBarApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.toolbar {
// Force expanded title bar
ToolbarItem(placement: .automatic) {
Spacer()
}
}
}
// Set title bar styles
.windowStyle(.titleBar)
.windowToolbarStyle(.unified(showsTitle: true))
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
for window in NSApp.windows {
// Set title bar to transparent, because can't be done in SwiftUI
window.titlebarAppearsTransparent = true
}
}
}
struct ContentView: View {
var body: some View {
ZStack(alignment: .top) {
ScrollView {
VStack(spacing: 16) {
// Add some scrollable content
ForEach(1...10, id: \.self) { _ in
RoundedRectangle(cornerRadius: 16, style: .continuous)
.fill(.foreground)
.opacity(0.9)
.frame(width: 300, height: 100)
}
}
.padding()
.frame(maxWidth: .infinity)
}
// Add custom title bar view
VisualEffectView(blendingMode: .withinWindow, material: .hudWindow)
// Make it appear below the actual title bar
.edgesIgnoringSafeArea(.top)
// Restrict the size to 0 points inside the safe area
// i.e. make it the size of the title bar safe area
.frame(height: 0)
}
.background(
// Add translucent background to window
VisualEffectView(blendingMode: .behindWindow, material: .underWindowBackground)
.edgesIgnoringSafeArea(.top)
)
.frame(minWidth: 400, maxWidth: .infinity, minHeight: 300, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct VisualEffectView: NSViewRepresentable {
var blendingMode: NSVisualEffectView.BlendingMode
var material: NSVisualEffectView.Material
func makeNSView(context: Context) -> NSVisualEffectView {
let view = NSVisualEffectView()
view.blendingMode = blendingMode
view.isEmphasized = true
view.material = material
return view
}
func updateNSView(_ nsView: NSVisualEffectView, context: Context) {}
}
@alexandersandberg
Copy link
Author

CleanShot 2022-10-20 at 18 18 05@2x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment