I have a window with two NSTextField controls whose values must be kept in sync with one another. Specifically, one is width and the other is length and the ratio of them should remain equal to a given aspect ratio. I want the user to be able to set whichever they prefer and have the other update automagically.
My first approach: I set the delegate for each of the two controls to be the window controller. I implemented the controlTextDidEndEditing method. I check the sender. If it was the width field, I calculated the height field and updated its value via the bound property (self.my_height = self.my_width/aspectRatio). Similarly, if it was the height field, (self.my_width = self.my_height*aspectRatio).
But I hit a snag. Assume that the aspect ratio was 1.5. The user enters 100 in the width field and then moves on to another field. The height field updates to 66 (for better or worse, I chose to always round down). The user clicks in the height field, makes NO change and the clicks elsewhere. The width field is updated to 99. The user is now scratching his/her head.
My refinement. I also implemented the controlTextDidChange method in the window controller. All this does is set a static (file scoped) BOOL variable (gTextFieldDidChange) to YES. Now, when I enter the controlTextDidEndEditing, I check the state of gTextFieldDidChange. If NO, then I return immediately. If YES, then I clear gTextFieldDidChange back to NO and handle the length/width updates.
This seems to be working without any problems for me, but it seems rather "back-door". Is there a cleaner/smarter approach that I'm missing?
Thanks for any/all suggestions. mike
The following code does what you want using
NSTextFieldDelegate>
methods:You can clone or download a small sample app from a Bitbucket Repository I've just made for you ;-)