xcodemacoscocoainterface-buildernscombobox

NSComboBox autocompletion with an NSValueTransformer


I want to make an NSComboBox with a list of predetermined values. The underlying objects are a custom Swift struct, and I'm using a custom NSValueTransformer to transform those to and from the underlying string representation I'm storing.

I want to limit the user to the options in the popup, but still allow autocompletion. I'm using a data source for it, and I'm using Cocoa bindings to a Core Data object, and tried using the KVO Core Data validation, like I'm using in a regular (non-combo) text field, but that field doesn't have a value transformer.

The first problem is that if I set the behavior to Selectable, the transformation happens correctly and the right value is saved, and the transformed values get passed to the KVO validation. But then the user can't type and get autocompletion. If I set Editable, then you're able to type and autocomplete, but no value gets transformed, validated, or saved.

I want the KVO validation in place, so that I can prevent the user from entering arbitrary values - I want autocompletion, but not freeform entry.

These are my Attributes and Bindings inspectors for the combo box:


Solution

  • An NSComboBox is designed to allow the user to input custom values in addition to a list of menu items, so it includes a text field. If you don’t want this behavior, an NSPopUpButton can be used, which just has a list of items. A pop-up button doesn’t have autocompletion per se, but like other menus, items can be selected by typing the name.