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:
- Entered new value to text field
- textField updates the bounded ViewController's property using the given ValueTransformer.reverseValueTransformed
- 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.