1

I have a NSSlider and a NSTextField which are both binded to a property (lets call it var X:CGFloat) of the ViewController class. I use a ValueTransformer to translate the float to a string with '%' sign (e.g. 5.0 -> "5.0%") I also implemented the reverse which would take the string (either with or without the suffix) and parse it to CGFloat (e.g. "5%" -> 5.0 or "5" -> 5)

So when the slider moves, it updates X to the slider value, and then the textField is being updated accordingly. My problem is when I insert a value via the text field. It does updates X and the slider, but I wish it would recall valueTransformed so that the textfield will show the formatted string of "%.1f\%" (e.g. if I inserted "56" and pressed enter, it would reformat it to: "56.0%")

In other words, I want to manually signal the textField to update its string value after it updated the bounded property value.

I've searched for a binding option but I couldn't find any clue. Also, I tried to manually call didChangedValue:ForKey whenever newValue is different from currentValue of X without success

tldr: I want the textField to reformat the text I entered (in case it is valid) to the "%.1f\%" form (e.g. "56" -> "56.0%") via the ValueConverter if possible

desired sequence:

  1. Entered new value to text field
  2. textField updates the bounded ViewController's property using the given ValueTransformer.reverseValueTransformed
  3. The freshly changed bounded ViewController's property updates the text field using ValueTransformer.valueTransformed

Workaround for similar case: As @JamesBucanek and @Willeke suggested, using NumberFormatter is really easy and convenient. I've successfully accomplished what I was trying to do with it. It is not the answer for my question but it did the trick. Thank you guys.

E1adi
  • 77
  • 4
  • If I understand what you're asking for, this should happen automatically when you exit the field (via `-validateEditing`). You don't want this to happen while the user is typing, or else you end up with a situation like [this](https://stackoverflow.com/questions/6337464/nsnumberformatter-doesnt-allow-typing-decimal-numbers). – James Bucanek Jun 02 '19 at 00:01
  • Remove the value converter and add a `NSNumberFormatter` to the text field. – Willeke Jun 02 '19 at 01:24
  • @JamesBucanek, Thank you for your answer, I configured the text field to send notification only when pressing Enter so I supposed it should act as you said, but it didn't. – E1adi Jun 02 '19 at 08:12
  • @Willeke, Thank you for your answer. I did dropped the value converter and used NumberFormatter instead which is highly customisable. – E1adi Jun 02 '19 at 08:13

0 Answers0