Re: Calling commitEditing text field loses focus
On Dec 20, 2011, at 5:14 AM, Christiaan Hofman wrote:
> I have a text field whose value is bound through an NSObjectController. Before performing certain
actions I call -commitEditing on that object controller to make sure I have the current value from the text
field. What I notice is that if there are any uncommitted changes to the text, the text field loses focus due
to this call. This is certainly not what I want, I just want to commit the edit. I also don't recall this to
happen in the past, but I am not sure for how long this has been going on. Also, the focus is not lost when the
text had not changed since the last commit. To me this sounds like a bug. Can anyone confirm this is a bug, or
tell me why this would make sense? Or tell me whether there is some kind of setting to change this behavior?
This how it has worked since NSController was introduced.
It is less than ideal for a number of reasons. (You need to commit editing before saving, but that really
shouldn’t change keyboard focus, nor should it change the user’s selection in many situations.)
If you want to solve this problem specifically, you can manually push the value through to the bound object
when the field is editing. (Make sure you also take care of the value transformer case. Yes, this feels a
little bit like you’ve given up most of the advantages of having bindings.)
A more general solution would be to write something like adding
- (void)commitEditingAndRestoreFirstResponderMumbleMumble;
to NSController. It’s a bit tedious to get this implementation right, since you have to handle
NSTextView, plus field editors for the various types of things which might use them, scrolling selection
ranges back into view, etc. This will take longer, but then you’ll have the problem solved centrally,
once and for all.
—Jim
(Continue reading)