how do I put some swiftUi code in my appkit app?

Generated on 7/30/2024

1 search

Tailscan

This post is brought to you by Tailscan, the best devtool for Tailwind CSS.

To integrate SwiftUI code into your AppKit app, you can use the NSHostingView class. This allows you to embed SwiftUI views within your AppKit view hierarchy. Here's a step-by-step guide on how to do this:

  1. Create Your SwiftUI View: Define the SwiftUI view that you want to embed in your AppKit app.

    import SwiftUI
    
    struct MySwiftUIView: View {
        var body: some View {
            Text("Hello, SwiftUI in AppKit!")
                .padding()
        }
    }
    
  2. Embed the SwiftUI View in AppKit: Use NSHostingView to embed the SwiftUI view in your AppKit view hierarchy.

    import Cocoa
    import SwiftUI
    
    class MyViewController: NSViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Create the SwiftUI view
            let swiftUIView = MySwiftUIView()
    
            // Create the hosting view with the SwiftUI view
            let hostingView = NSHostingView(rootView: swiftUIView)
    
            // Add the hosting view to the view controller's view hierarchy
            self.view.addSubview(hostingView)
    
            // Set constraints or frame for the hosting view
            hostingView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                hostingView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
                hostingView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
                hostingView.topAnchor.constraint(equalTo: self.view.topAnchor),
                hostingView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
            ])
        }
    }
    
  3. Using SwiftUI Menus in AppKit: You can also use SwiftUI menus in your AppKit app by utilizing NSHostingMenu, a new NSMenu subclass.

    import Cocoa
    import SwiftUI
    
    // Define your SwiftUI menu
    struct MyMenu: View {
        var body: some View {
            Menu {
                Button("Option 1", action: { print("Option 1 selected") })
                Button("Option 2", action: { print("Option 2 selected") })
            } label: {
                Text("My Menu")
            }
        }
    }
    
    // Create an NSHostingMenu with the SwiftUI menu
    let hostingMenu = NSHostingMenu(rootView: MyMenu())
    

For more detailed information, you can refer to the What’s new in AppKit session from WWDC 2024, which covers the integration of SwiftUI with AppKit, including using NSHostingView and NSHostingMenu.

Relevant Sessions

how do I put some swiftUi code in my appkit app? | Ask WWDC