如何为基于AppKit的macOS SwiftUI应用设置主窗口标题?
Hey there! Let's fix that missing window title issue for your macOS app. Since you're using a mix of AppKit and SwiftUI and couldn't find a "title segment" in Main.storyboard, here are a few practical approaches to add a title to your window:
Method 1: Use SwiftUI Environment to Access NSWindow
This works great if you're using the modern SwiftUI App lifecycle (macOS 11+):
- First, add an environment key to pass the
NSWindowreference to your views:
private extension EnvironmentValues { var window: NSWindow? { get { self[WindowKey.self] } set { self[WindowKey.self] = newValue } } } private struct WindowKey: EnvironmentKey { static let defaultValue: NSWindow? = nil }
- Inject the window reference in your app's entry point:
@main struct WebViewApp: App { var body: some Scene { WindowGroup { ContentView() .environment(\.window, NSApplication.shared.windows.first) } } }
- Set the title in your main view when it appears:
struct ContentView: View { @Environment(\.window) private var window var body: some View { WKWebView(url: URL(string: "https://your-target-url.com")!) .onAppear { window?.title = "My Web Browser" // Replace with your desired title // Optional: Ensure title is visible if using transparent title bar window?.titleVisibility = .visible } } }
Method 2: Set Title via AppKit's NSViewController
If you're using a storyboard with an NSViewController hosting your SwiftUI view, you can set the title directly in the view controller:
class MainViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Set window title here self.view.window?.title = "My Web View App" // If you're embedding SwiftUI content: self.view = NSHostingView(rootView: ContentView()) } }
Method 3: Create NSWindow Manually (No Storyboard)
If you're ditching the storyboard entirely and creating the window programmatically, set the title when initializing the window:
@main struct WebViewApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate } class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Create a window with standard titled style let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 800, height: 600), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) window.title = "Custom Web View App" // Your title here window.center() window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) } }
Quick Check: Ensure Window Style Includes Titled
If your window still doesn't show a title, double-check that the window's style mask includes .titled. Without this flag, the title bar (and title) won't appear at all.
内容的提问来源于stack exchange,提问作者esaruoho

