Hello chat, I am trying to build a simple macOS app and for this base template, I want…
- User
Hello chat, I am trying to build a simple macOS app and for this base template, I want to see how to make the background translucent blur like is many of the side panels you would find in the finder app for example. How can I modify this code for that? Also, how do I set the window dimensions to 960 by 960?
// // ContentView.swift // Daily 48 // // Created by Luxe Life on 1/9/24. //
import SwiftUI
struct ContentView: View { var body: some View { VStack { Image(systemName: "pencil") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, Daily 48") Text("Second Line") } .padding() } }
#Preview { ContentView() }
- Assistant
To create the translucent blur effect in your macOS app similar to what you see in Finder side panels, you can use the
VisualEffectViewfrom AppKit, which is not directly available in SwiftUI. However, you can wrap it in a SwiftUI view with the help of anNSVisualEffectViewwrapper.Here's how you can update your SwiftUI view to include a blurred background and set the window dimensions to 960x960. First, you'll need to create the
NSVisualEffectViewwrapper:import SwiftUI import AppKit struct VisualEffectView: NSViewRepresentable { var material: NSVisualEffectView.Material var blendingMode: NSVisualEffectView.BlendingMode func makeNSView(context: Context) -> NSVisualEffectView { let view = NSVisualEffectView() view.material = material view.blendingMode = blendingMode view.state = .active return view } func updateNSView(_ nsView: NSVisualEffectView, context: Context) { nsView.material = material nsView.blendingMode = blendingMode } } struct ContentView: View { var body: some View { ZStack { VisualEffectView(material: .sidebar, blendingMode: .behindWindow) VStack { Image(systemName: "pencil") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, Daily 48") Text("Second Line") } .padding() } } } // Preview Provider struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }To set the window dimensions to 960x960, you need to adjust the window size when you create the window in your
AppSwiftUI file, which is usually namedAppNameApp.swift. Here's a rough example of how you might set the window size:import SwiftUI @main struct Daily48App: App { var body: some Scene { WindowGroup { ContentView() .frame(width: 960, height: 960) } } }Please note that the
framemodifier in theWindowGroupwill set the initial size of the window's content view but won't prevent the user from resizing the window. If you want to set minimum or maximum sizes or disable resizing altogether, you would need to access theNSWindowdirectly, which is not as straightforward in SwiftUI as it is in AppKit. If you need to do that, you may need to create a custom window controller in AppKit and integrate it with your SwiftUI app. - User
When I change the values of the window as im trying to make it square, it does not seem to change.
@main struct Daily48App: App { var body: some Scene { WindowGroup { ContentView() .frame(width: 333, height: 333) } } }
- Assistant
The
.framemodifier in SwiftUI adjusts the size of the view within its parent and does not directly control the window dimensions. To specify the window size in a SwiftUI macOS app, you need to use thewindowCommandsto customize the window settings such as size, min, and max dimensions.To ensure the window is square and has a size of 960x960 pixels, you will need to configure the window in your App struct using the
.windowStyleand.windowToolbarStylemodifiers.Here's an example of how you can set the window to be square and have fixed dimensions in your
Daily48App:import SwiftUI @main struct Daily48App: App { var body: some Scene { WindowGroup { ContentView() } .windowStyle(HiddenTitleBarWindowStyle()) // or DefaultWindowStyle() if you want the title bar .commands { CommandGroup(replacing: .newItem) { } } .windowToolbarStyle(UnifiedCompactWindowToolbarStyle()) .windowStyle(DefaultWindowStyle()) .frame(minWidth: 960, idealWidth: 960, maxWidth: 960, minHeight: 960, idealHeight: 960, maxHeight: 960) } }In the above code, the
.windowStyle(DefaultWindowStyle())line shows the title bar. If you want to hide the title bar, you can use.windowStyle(HiddenTitleBarWindowStyle())instead.The
.framemodifier is now specifying the minimum, ideal, and maximum width and height for the window, enforcing that the window will be 960x960 and not resizable.Please be sure that you're using the correct project file and that you're modifying the
@mainstruct of your application. These modifications should adjust the window size accordingly when you run your app. - User
I get this error: Value of type 'some Scene' has no member 'frame'
Whats wrong here?
- Assistant
I apologize for the confusion. The
.framemodifier is not applicable to theScenein SwiftUI; it's only for views. Setting the window size for a macOS app in SwiftUI is different from setting the frame for a view.To set the window size for a macOS app, you typically use the
windowGroupAPI and set the window size with theNSWindowobject. However, SwiftUI does not provide a direct way to set the window size in theScene. Instead, you need to use theNSApplicationDelegateandNSWindowDelegateto achieve this.Here's an example of how to set up a SwiftUI macOS app with a specific window size:
- Create an
AppDelegateclass conforming toNSApplicationDelegateandNSWindowDelegate:
import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ notification: Notification) { // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 960, height: 960), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) window.delegate = self } func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize { // Keep the window square return NSSize(width: 960, height: 960) } }- Then update your main
Appstruct to use this delegate:
@main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } .commands { CommandGroup(replacing: .newItem) {} } } }In this setup, we're using the
@NSApplicationDelegateAdaptorproperty wrapper to integrate theAppDelegatewith our SwiftUI application lifecycle. TheAppDelegatesets up the window with a 960x960 size and makes it key and front on launch. ThewindowWillResizedelegate method ensures the window remains square when resized.As of my knowledge cutoff in early 2023, there is no built-in SwiftUI API to set a fixed window size directly in the
Scene, so we have to rely on AppKit integration as shown above. Please note that usage ofAppDelegateandScenemay evolve with future updates of SwiftUI and macOS. - Create an
- User
Okay so the transparent window and size works, but why is my xcode opening up two windows? One is square and the other is rectange, why?
// // Daily_48App.swift // Daily 48 // // Created by Luxe Life on 1/9/24. // License GPL 0.0.0
import Cocoa import SwiftUI
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { var window: NSWindow!
func applicationDidFinishLaunching(_ notification: Notification) { // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 888, height: 888), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) window.delegate = self } func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize { // Keep the window square return NSSize(width: 888, height: 888) }}
@main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene { WindowGroup { ContentView() } .commands { CommandGroup(replacing: .newItem) {} } }}
One window appears to be correct and the other is not. I just want the one window.
- Assistant
When you use the
NSApplicationDelegateAdaptorproperty, you're providing a customNSApplicationDelegatefor your SwiftUI app. However, theWindowGroupin theAppbody is also creating a window, which is why you're seeing two windows.To solve this issue, you need to remove the
WindowGroupfrom theAppbody since you're manually creating a window in theAppDelegate. YourAppstruct should look like this instead:@main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { EmptyView() // Instead of WindowGroup, provide an empty view .commands { CommandGroup(replacing: .newItem) {} } } }By providing an
EmptyView, you're effectively telling SwiftUI not to create a default window. YourAppDelegateis responsible for creating the window manually, and thus you should end up with only one window—the one you've configured in theAppDelegate. - User
Now I get this error: Value of type 'EmptyView' has no member 'commands'
- Assistant
My apologies for the confusion. You cannot directly apply the
.commandsmodifier to anEmptyView. Instead, you should return anEmptyScene(which does not create a window) and use the.commandsmodifier on theSceneitself.Here's how to modify your
Daily48Appstruct to avoid creating an additional window:@main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { // This returns an empty scene that does not create a window. EmptyScene() .commands { CommandGroup(replacing: .newItem) {} } } } // An empty scene can be defined like this: struct EmptyScene: Scene { var body: some Scene { // We don’t return any view here because we are manually creating the window in AppDelegate. EmptyView() } }In this code, we define an
EmptyScenestruct, which returns anEmptyViewin itsbody. In theDaily48App, we instantiate thisEmptySceneand apply the.commandsmodifier to it directly. This ensures that no default window is created by SwiftUI, and you're left with just the window created in theAppDelegate. - User
still a new error:Static method 'buildExpression' requires that 'EmptyView' conform to 'Scene'
// // Daily_48App.swift // Daily 48 // // Created by Luxe Life on 1/9/24. // License GPL 0.0.0
import Cocoa import SwiftUI
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { var window: NSWindow!
func applicationDidFinishLaunching(_ notification: Notification) { // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 888, height: 888), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) window.delegate = self } func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize { // Keep the window square return NSSize(width: 888, height: 888) }}
@main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene { // This returns an empty scene that does not create a window. EmptyScene() .commands { CommandGroup(replacing: .newItem) {} } }}
// An empty scene can be defined like this: struct EmptyScene: Scene { var body: some Scene { // We don’t return any view here because we are manually creating the window in AppDelegate. EmptyView() } }
- Assistant
I apologize for the confusion. My previous example was incorrect;
EmptyViewdoes not conform toScene, and so you can't use it to define the body of aScene.To prevent SwiftUI from automatically creating an additional window, you should use an
NSApplicationDelegateto handle the creation of your window and simply not define aWindowGroupin yourAppstruct. Additionally, the.commandsmodifier should be applied to theScenelevel, not to theEmptyView.Here's the corrected code:
import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ notification: Notification) { // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 888, height: 888), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.isReleasedWhenClosed = false window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) } } @main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { // Since we don't define a WindowGroup, no default window is created. Settings { EmptyView() } .commands { CommandGroup(replacing: .newItem) {} } } }In this example:
- We omit the
WindowGroupentirely, which means SwiftUI won't create a window automatically. - We use a
Settingsscene with anEmptyViewto satisfy the requirement for theAppbody to have at least one scene. TheSettingsscene doesn't create a new window. - We apply the
.commandsmodifier at the scene level, which doesn't impact window creation.
When you run this code, only the window created and managed by the
AppDelegateshould appear, and there should be no additional windows. - We omit the
- User
Perfect, almost there now to a base template I can use. Now, what I'd like to do is see how to make the titlebar of this window transparent just like many of the macOS windows. I like how clean it is.
// // Daily_48App.swift // Daily 48 // // Created by Luxe Life on 1/9/24. // License GPL 0.0.0
import Cocoa import SwiftUI
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { var window: NSWindow!
func applicationDidFinishLaunching(_ notification: Notification) { // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 222, height: 666), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.isReleasedWhenClosed = false window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) }}
@main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene { // Since we don't define a WindowGroup, no default window is created. Settings { EmptyView() } .commands { CommandGroup(replacing: .newItem) {} } }}
- Assistant
To make the title bar of your window transparent and give it a modern, clean look like many macOS apps, you will need to modify the window's title bar appearance and possibly the content layout.
Here's how you can modify your
AppDelegateto achieve a transparent title bar:import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ notification: Notification) { // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 222, height: 666), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.isReleasedWhenClosed = false window.titlebarAppearsTransparent = true // Make the titlebar transparent window.titleVisibility = .hidden // Hide the title text window.styleMask.insert(.fullSizeContentView) // Allow content to extend behind the title bar window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) // Customize appearance for a transparent effect if let titlebar = window.standardWindowButton(.closeButton)?.superview { titlebar.wantsLayer = true titlebar.layer?.backgroundColor = NSColor.clear.cgColor } } } @main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { // Since we don't define a WindowGroup, no default window is created. Settings { EmptyView() } .commands { CommandGroup(replacing: .newItem) {} } } }In this updated
AppDelegate, we've setwindow.titlebarAppearsTransparenttotrue, which makes the title bar transparent. Thewindow.titleVisibilityis set to.hiddento hide the title text. We also ensure that thewindow.styleMaskincludes.fullSizeContentViewto allow the content to extend under the title bar.Additionally, we access the title bar view directly and set its layer's background color to clear, ensuring the transparency effect. Keep in mind that customizing the title bar may affect the standard window buttons (close, minimize, and zoom), so make sure that they remain accessible and visible as needed.
Please note that the look and behavior may vary depending on the version of macOS and the system settings for title bars and windows. Adjustments may be necessary to achieve the exact appearance you want.
- User
the titlebar did not end up blending in. I want it to look like how the minimize and expand buttons are over a transparent background like in the macOS finder window. My app did not appear to change. It is slightly transparent now that I give it a second look. Is there a way to make it fully transparent above it's NSBlurred background?
- Assistant
To achieve the effect where the window controls (close, minimize, and maximize buttons) seem to float over a transparent or blurred background—like in many modern macOS apps—you need to customize the window's title bar further. This typically involves using private APIs, which is not officially supported by Apple and could potentially break in future updates of macOS. However, for educational purposes, I can show you a commonly used approach to achieve this effect.
Here's how you can update your
AppDelegateto make the title bar fully transparent:import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ notification: Notification) { // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 222, height: 666), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.isReleasedWhenClosed = false window.titlebarAppearsTransparent = true window.titleVisibility = .hidden window.styleMask.insert(.fullSizeContentView) // Make the title bar completely transparent window.standardWindowButton(.closeButton)?.superview?.subviews.forEach { subview in if subview.isKind(of: NSVisualEffectView.self) { subview.isHidden = true } } // Set up the content view with a visual effect view for the blurred background let contentView = window.contentView! let visualEffectView = NSVisualEffectView(frame: contentView.bounds) visualEffectView.blendingMode = .behindWindow visualEffectView.material = .sidebar visualEffectView.state = .active visualEffectView.autoresizingMask = [.width, .height] // Resize with the window // Add the visual effect view as the first subview of the content view contentView.addSubview(visualEffectView, positioned: .below, relativeTo: nil) // Add the SwiftUI view on top of the visual effect view let hostingView = NSHostingView(rootView: ContentView()) hostingView.frame = contentView.bounds hostingView.autoresizingMask = [.width, .height] // Resize with the window contentView.addSubview(hostingView) window.makeKeyAndOrderFront(nil) } } @main struct Daily48App: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { // Since we don't define a WindowGroup, no default window is created. Settings { EmptyView() } .commands { CommandGroup(replacing: .newItem) {} } } }In this code:
- We iterate over the subviews of the title bar's superview (which contains the window buttons and potentially other views) and hide any
NSVisualEffectView. This is done to remove the default light or dark material of the title bar, which would otherwise obstruct the transparency. - We create an
NSVisualEffectViewwith the desired material and blending mode to provide a blurred background, and add it to the window's content view. This will underlay the entire window's content, including where the title bar would be, giving the appearance of a blurred background behind the window controls. - We then add the
NSHostingViewcontaining the SwiftUI content on top of theNSVisualEffectView.
Please remember that this approach relies on the internal view hierarchy of
NSWindow, which is not part of the public API and may change in future updates of macOS. Use such modifications with caution, especially if you plan to distribute your app on the Mac App Store, as it may not pass Apple's review guidelines.Always test thoroughly with each new macOS release to ensure compatibility.
- We iterate over the subviews of the title bar's superview (which contains the window buttons and potentially other views) and hide any
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.