How to set initial width of NSSearchToolbarItem

235 views Asked by At

The default width of NSSearchToolbarItem is way too large. I want it to be similar to the Notes app.

Is there an official way to do this?

The control has a property preferredWidthForSearchField, but this has no effect, which could also be one of the many Big Sur bugs.

The classic but deprecated minSize and maxSize settings seems to work, but then the control loses the ability to automatically resize itself according the available toolbar space.

2

There are 2 answers

0
Ely On

Maybe not the best way, but this seems to work:

searchToolbarItem.searchField.addConstraint(NSLayoutConstraint(item: searchToolbarItem.searchField, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .width, multiplier: 1, constant: 200) )
searchToolbarItem.searchField.addConstraint(NSLayoutConstraint(item: searchToolbarItem.searchField, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .width, multiplier: 1, constant: 30) )
0
Vicente Garcia On

Swift 5

Based on the already given answer.

let search = NSSearchToolbarItem()
search.searchField.widthAnchor.constraint(equalToConstant: 200).isActive = true