david-swift e989bea14e
All checks were successful
Deploy Docs / publish (push) Successful in 2m38s
Initial commit
2024-12-02 22:14:13 +01:00

1.2 KiB

SwiftUI Integration

Learn how to render SwiftUI views in a macOS app.

Simple Views

Wrap a SwiftUI view by creating a widget conforming to SwiftUIWidget. Define your SwiftUI view in the SwiftUIWidget/view(properties:) function.

import MacBackend
import SwiftUI

struct Label: SwiftUIWidget {

    var label: String
    var icon: MacBackend.Icon

    static func view(properties: Self) -> some SwiftUI.View {
        SwiftUI.Label {
            SwiftUI.Text(properties.label)
        } icon: {
            properties.icon.image
        }
    }

}

Container Views

It is possible to pass MacBackend views as child views to SwiftUI views. Add them to SwiftUIWidget/wrappedViews and reference via the identifier.

import MacBackend
import SwiftUI

struct ContainerView: SwiftUIWidget {

    var child: Body

    init(@MacBackend.ViewBuilder child: () -> Body) {
        self.child = child()
    }

    var wrappedViews: [String: MacBackend.AnyView] {
        [.mainContent: child]
    }

    func view(properties: Self) -> some SwiftUI.View {
        MacBackendView(.mainContent)
            .background(.red)
    }

}

You can add new wrapped views or delete old ones dynamically.