Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI NSTitlebarAccessoryViewController

Tags:

macos

swiftui

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)
        }
    }
}
like image 255
Taylor Avatar asked May 31 '26 04:05

Taylor


1 Answers

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.

like image 85
Taylor Avatar answered Jun 02 '26 20:06

Taylor