0

I'm wondering if it's possible to dynamically create NSTouchBar items. In my app I've got a dataSource protocol to fill the contents of an NSTableViewController. I'd like to use this protocol to also fill the touchBar with the same options.

This is the protocol I'm using.

protocol RestaurantsViewControllerDelegate {
    func numberOfRestaurants(in restaurantsViewController: RestaurantsViewController) -> Int
    func restaurantsViewController(_ restaurantsViewController: RestaurantsViewController, restaurantAtIndex index: Int) -> Restaurant
    func restaurantsViewController(_ restaurantsViewController: RestaurantsViewController, didSelectRestaurant restaurant: Restaurant)
}

The only code that I've found only, though, suggests that I have to manually create each button, like so.

@available(OSX 10.12.1, *)
extension NSTouchBarItem.Identifier {
    static let restaurant = NSTouchBarItem.Identifier("my.custom.identifier")
}

extension RestaurantsViewController: NSTouchBarDelegate {
    override func makeTouchBar() -> NSTouchBar? {
        let touchBar = NSTouchBar()
        touchBar.delegate = self
        touchBar.defaultItemIdentifiers = [.restaurant]
        return touchBar
    }

    func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
        switch identifier {

        case NSTouchBarItem.Identifier.restaurant:
            let item = NSCustomTouchBarItem(identifier: identifier)
            item.view = NSButton(title: "This is a restaurant", target: nil, action: nil)
            return item
        default: return nil
        }
    }
}

Is there any way to what I'd like to do?

user4992124
  • 1,574
  • 1
  • 17
  • 35

1 Answers1

0

NSTouchBarItem.Identifier can be based on any string, including dynamic ones based on some identifier of the Restaurant object. You could set the defaultItemIdentifiers to that array of dynamically generated identifiers, and then touchBar(_:,makeItemForIdentifier:) will be called for each of those identifiers (which you can then dynmically create a button or otherwise for each of those identifiers).

Another alternative is to use NSScrubber. This could be a single item in the Touch Bar, but then it has a DataSource that could be used to populate it based on your Restaurant data source.

Taylor
  • 3,183
  • 17
  • 18