create a swiftui app using nsapplication in swift

To create a SwiftUI app using NSApplication, you can follow these steps:

  1. Create a new SwiftUI project in Xcode for macOS.
  2. In the project navigator, select the folder that contains the AppDelegate.swift file.
  3. Add the following code to the AppDelegate.swift file to create a new instance of NSApplication and make it the shared application:
main.swift
import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view that provides the window contents
        let contentView = ContentView()

        // Create a window to host the SwiftUI view
        let window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: contentView)
        self.window = window
        window.makeKeyAndOrderFront(nil)

        // Create a new NSApplication instance and set it as the shared application
        let app = NSApplication.shared
        app.setActivationPolicy(.regular)
        app.activate(ignoringOtherApps: true)
        app.run()
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


}
1174 chars
36 lines
  1. This code creates a NSWindow from the ContentView struct defined in ContentView.swift, and sets it as the content view of the NSHostingView object.

  2. Finally, it creates a new instance of NSApplication, sets its activation policy to regular, activates it, and runs it.

That's it! You can now build and run your app to see the NSWindow containing your SwiftUI view.

gistlibby LogSnag