views:

25

answers:

1

I would like to make some bindings that toggle item titles in a popup menu based on a single numerical value in a text field. Let me explain:

This is my UI:

a text field and a pop up menu

the pop up menu

I want my menu items to automatically adjust to singular or plural based on the number in the text field. For example, when I type "1" in the box, I want the menu items to be labeled "minute", "hour" and "day". When I type "4", I want the menu items to be labeled "minutes", "hours" and "days".

What I did to date:

  1. I bound the three menu item's labels to the same key path as the text field's value.
  2. I created an NSValueTransformer subclass to interpret the value in the text field and return singular or plural to be used as item titles.
  3. I applied this value transformer to the three bindings.

The issue:

My value transformer can either return singular or plural but it can't set the appropriate string based on the menu item it's applied to.

It looks to me like a value transformer is generic and can't return different values for different destinations. That would mean that to have the three titles change automatically, I would need to have three different value transformers that return the appropriate string for each menu item. That doesn't seem optimal at all.

Ideally I would be able to combine a string stored in the destination menu item (let's say in the item's tag property) with an "s" in the value transformer when the text field's value is larger than one, or something similar that would enable me to use a single value transformer for all the menu items.

Is there something I missed? What would be an ideal solution?

+1  A: 

Okay, this is probably not an ideal solution, but something you could consider: if you set your value transformers from your code (and not in IB), you could instantiate 3 different transformers of the same class. You could give your value transformer an ivar NSString *unit (and add something like [[MyValueTransformer alloc] initWithUnit:]) to allow each to return their own string, but you still have to write the value transformer's code only once.

(Also, if you're ever going to consider making your application localizable, simply appending an "s" to create the plurals is not going to work. You could of course add ivars for both NSString *singular and NSString *plural to do that.)


Edit: Wait, I just realized you can register value transformers! If you register them as MyValueTransformerHours and MyValueTransformerMinutes (by manually allocating and initializing them in your code), you can use them from Interface Builder. See also https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ValueTransformers/Concepts/Registration.html#//apple_ref/doc/uid/20002166-BAJEAIEE.

xnyhps
Awesome! Your edit is exactly what I need. It's not a no-code solution but it's pretty damn near. Thanks!
Form