Created
October 20, 2022 16:18
-
-
Save alexandersandberg/91bc09deb3b8d2d59b445301648fbdfe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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) {} | |
} |
Author
alexandersandberg
commented
Oct 20, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment