macos-sierranstouchbar

How do you create a NSTouchBarItem that uses the remaining width in the Touch Bar?


I'm trying to create a NSButton that takes up the remaining space on the Touch Bar. My goal is to have a button similar to the "Search or enter website name" button in Safari.

I've looked at setting constraints with widthAnchor, but I'm completely lost at how to set it properly.


Solution

  • NSButton has an intrinsicContentSize that fits its content, and a default horizontal contentHuggingPriority of 750 (NSLayoutPriorityDefaultHigh), meaning it will strongly try to match that content width.

    You can decrease that hugging priority (e.g. [button setContentHuggingPriority:1.0 forOrientation:NSLayoutConstraintOrientationHorizontal]) in order to make it more able to stretch away from that content, and in this case fill up the extra space in the touch bar.