Update NSTouchBar on the fly to add / remove items programmatically

I am currently implementing NSTouchBar api for my macOS application.

At this point, the only touchpad I have on it has a main view controller as its delegate, and I can add elements to it. The trick, I need some of these elements to be displayed only when a certain condition is met (a row is selected in the table).

I have a boolean value indicating whether the button should be visible. How to update NSTouchBar on the fly to show / hide this button if my logical changes? (I don’t need to observe this logical one, I could just make a call to update in another method that I already implemented)

What I did now is this: in touchBar(:makeItemForIdentifier) I have a switch for all identifiers, and under the correct case I either return NSCustomTouchBarItem with a button, or nil if my boolean is false .

I tried calling makeTouchBar again after selecting a table row, but it does not update the visibility of the buttons, as if touchBar(:makeItemForIdentifier) not called again.

Thanks!

+5
source share
2 answers

Four ideas:

  • Try changing the defaultItemIdentifiers to the set of identifiers for the elements that should be displayed. Please note that this would be problematic if the user set up the touchpad, but I think that file sharing on demand and touchpad setup still do not work together. This also has the advantage that you do not need to return zero in touchBar(:makeItemForIdentifier:) .
  • Calling makeTouchBar() will create a new NSTouchBar instance, but will not change the touchBar property. Try something like

     viewController.touchBar = viewController.makeTouchBar() 

    or

     viewController.touchBar = nil 
    1. Set the touchBar property to NSTableRowView , which should display additional elements when selected, and be sure to include otherItemsProxy in defaultItemIdentifiers . Since the contents of the touchpad consist of all the elements in the responder chain, this may include the touchBar property of the touchBar row (provided that it can become the first responder).

    2. Are you sure these items should be hidden if the row is not selected? Consider disabling them (for example, setting the enabled property for buttons that they contain in false ).

+7
source

Just lock the touchpad in the view controller:

self.touchbar = nil

Then, the makeTouchBar() delegate method is automatically called. Using your flags, you can easily select icons.

EDIT: This solution has been tested and works great.

+3
source

Source: https://habr.com/ru/post/1260197/