How do I use an NSFormatter subclass with an NSPop

2019-08-18 20:28发布

问题:

I want to use an NSFormatter subclass to format the contents of an NSPopUpButton I'm using to display a list of choices.

Basically I have an NSArray of MyObjects which is bound to the NSPopUpButton via the Content Values binding and I want to display something in the pop up menu other than what is returned by -description. I don't really want to use a transformer because then I have to create an entirely new array and transform each object into a string before adding it to the new array.

Using setFormatter: on the NSPopUpButton itself via either IB or code doesn't work, I suspect because only the formatter for the individual cell is applied to the items in the list.

Is there an easy way to set a formatter for all the cells of the NSPopUpButton? Basically I want to just be able to set it once and forget about it.

回答1:

Typically you'd bind your popup button to an array controller that contains custom model objects (through the content binding), and use the content values binding to specify a keypath on those object with the string you want to use as the title.

From what I understand, you have an array of plain strings you want to use as the data source, only you want to display a different string for the title, right?

I'm not sure why making a data transformer wouldn't work if set up like the above-- or maybe I'm misunderstanding something? You'd have one binding to the actual string, and another binding to the string using a transformer, but both of them would be using the same array controller. Your other options are creating a model class to wrap around the strings and provide a title property, or creating a category on NSString that returns your title to use as the display value binding. In all of these cases you can create your own NSFormatter in code and use it to return the correct string title.