Taylor
Taylor

Reputation: 6430

SwiftUI NSTitlebarAccessoryViewController

I'd like to use the SwiftUI app lifecycle, but my app uses NSTitlebarAccessoryViewController to show a bar of tool options below the toolbar:

toolbar

Specifically, I'm doing this:

        let toolSettingsView = NSHostingView(rootView: ToolAccessoryView(model: model))
        let vc = NSTitlebarAccessoryViewController()
        vc.view = toolSettingsView
        vc.fullScreenMinHeight = accessoryHeight // Ensure tool settings are visible in full screen.
        toolSettingsView.frame.size = toolSettingsView.fittingSize
        window?.addTitlebarAccessoryViewController(vc)

Is there a (practical) way I can mimic the control appearance (of the sliders, etc.) using pure SwiftUI? When use a SwiftUI view I get this:

enter image description here

Code looks like this:

struct MainView: View {
    
    var model: DataModel
    var undoManager: UndoManager
    
    var body: some View {
        VStack {
            ToolAccessoryView(model: model)
            SculptingView(model: model, undoManager: undoManager)
        }
    }
}

Upvotes: 9

Views: 434

Answers (1)

Taylor
Taylor

Reputation: 6430

This is implemented as of macOS 13 by using a custom toolbar placement identifier as follows:

extension ToolbarItemPlacement {
    static let toolOptionsBar = ToolbarItemPlacement(id: "com.companyname.toolOptions")
}

Then specifying the placement in the .toolbar:

ToolbarItem(placement: .toolOptionsBar) {
    ToolAccessoryView()
}

Which in my case looks like this:

toolbar accessory view

The colors on the sliders are a bit odd, which is likely their bug.

See also https://developer.apple.com/documentation/swiftui/toolbarplacement/init(id:) which has some example code.

Upvotes: 1

Related Questions