How to add a view to NSGroupTouchBarItem

264 Views Asked by At

Trying to make a mutable list of buttons that show on the touch bar

override func windowDidLoad() {
    super.windowDidLoad()
    let customViewItem = NSCustomTouchBarItem(identifier: NSTouchBarItemIdentifier(rawValue: "identifier"))
    customViewItem.view = NSTextField(labelWithString: " ")
    groupTouchBarItem.view?.addSubview(customViewItem)
}

But I get Cannot invoke 'addSubview' with an argument list of type '(NSCustomTouchBarItem)' on the bottom line.

How can I add buttons to the touch bar and remove them at will? Is there an array I can through views into or should I always addSubview on the touchbar view?

1

There are 1 best solutions below

0
On

I'd recommend checking out this guide on creating NSTouchBar and NSTouchBarItems, specifically "NSTouchBar Objects", "Using NSTouchBarItem Objects"; as well as the documentation for NSGroupTouchBarItem

In short, when you create Touch Bar content you do so by composing NSTouchBarItems into an NSTouchBar, and not their views. (You primarily only deal with views when setting them on NSCustomTouchBarItems) And with NSGroupTouchBarItem, you are adding additional items to its groupTouchBar.

There are some conveniences, e.g.: NSGroupTouchBarItem(identifier: .myGroupItem, items: [customViewItem]), but you can also incrementally add to it with:

 groupItem.groupTouchBar.templateItems.insert(customViewItem)
 groupItem.groupTouchBar.defaultItemIdentifiers.append(customViewItem.identifier)