how do I put some swiftUi code in my appkit app?
Asked on 2024-07-30
1 search
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:
-
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() } } -
Embed the SwiftUI View in AppKit: Use
NSHostingViewto 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) ]) } } -
Using SwiftUI Menus in AppKit: You can also use SwiftUI menus in your AppKit app by utilizing
NSHostingMenu, a newNSMenusubclass.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

Enhance your UI animations and transitions
Explore how to adopt the zoom transition in navigation and presentations to increase the sense of continuity in your app, and learn how to animate UIKit views with SwiftUI animations to make it easier to build animations that feel continuous.

SwiftUI essentials
Join us on a tour of SwiftUI, Apple’s declarative user interface framework. Learn essential concepts for building apps in SwiftUI, like views, state variables, and layout. Discover the breadth of APIs for building fully featured experiences and crafting unique custom components. Whether you’re brand new to SwiftUI or an experienced developer, you’ll learn how to take advantage of what SwiftUI has to offer when building great apps.

Platforms State of the Union
Discover the newest advancements on Apple platforms.
