selectText of NSTextField on focus

后端 未结 5 1747
既然无缘
既然无缘 2021-02-04 10:17

Could anybody suggest a method to select all the text of an NSTextField when the user clicks it?

I did find suggestions to subclass NSTextField

5条回答
  •  甜味超标
    2021-02-04 10:54

    The answer from @Rob presumably worked at one point, but as @Daniel noted, it does not work any more. It looks like Cocoa wants to track the mouse and drag out a selection in response to a click, and trying to select the text in response to becomeFirstResponder does not play well with that.

    The mouse event needs to be intercepted, then, to prevent that tracking. More or less by trial and error, I've found a solution which seems to work on OS X 10.10:

    @interface MyAutoselectTextField : NSTextField
    @end
    
    @implementation MyAutoselectTextField
    - (void)mouseDown:(NSEvent *)theEvent
    {
        [[self currentEditor] selectAll:nil];
    }
    @end
    

    As far as I can tell, by the time mouseDown: gets called the field editor has already been set up, probably as a side effect of becomeFirstResponder. Calling selectAll: then selects the contents of the field editor. Calling selectText: on self instead does not work well, presumably because the field editor is set up. Note that the override of mouseDown: here does not call super; super would run a tracking loop that would drag out a selection, and we don't want that behavior. Note that this mouseDown: override doesn't affect selection once the textfield has become first responder, because at that point it is the field editor's mouseDown: that is getting called.

    I have no idea what range of OS X versions this works across; if you care, you'll need to test it. Unfortunately, working with NSTextField is always a little fragile because the way field editors work is so strange and so dependent upon the implementation details in super.

提交回复
热议问题