Focus a NSTextField without selecting | 19. April 2009 um 12:52 Uhr / Programming
It took me about three months to find this out, so I post it here so all the people who are looking possibly can find it.
I wanted a NSTextField to gain focus without selecting the whole text. While there is the method [NSTextField selectText:(id *)sender] and the [NSWindow makeFirstResponder:(NSTextField *)yourTextField] they all focus the NSTextField but also select the whole text so if you start typing you lose all the text which already is in the text field.
I wanted to have a button which adds some text to the textarea and than selexts it so you can continue to write behind the text.
The magic is to use the method setSelectedRange but it is not a NSTextField method instead a NSText method. You get this NSText with help of the [NSTextField currentEditor] method.
After that you set the rage length to 0 and the position to the length of the string which you get with [[textField stringValue] length]
I needed it for RubyCocoa and there it looks like that:
def select_input_field @input.selectText self range = OSX::NSRange.new(@input.stringValue.length, 0) @input.currentEditor.setSelectedRange range end
For Objective-C it should look like that:
- (IBAction)focusInputField:(id)sender {
[textField selectText:self];
[[textField currentEditor] setSelectedRange:NSMakeRange([[textField stringValue] length], 0)];
}
Hope this helps out someone :-).




abonnieren.
Anonym schrieb am 17.03.2010
Thank you much. That's a gem!
Shared files aus Bonn schrieb am 01.11.2010
Thanks for the post! The only thing which should be noted is that with a text FIELD this is not as straightforward (not that it was anyway), because the text field doesn’t keep a layout manager. I’m not sure how fields perform text layout – perhaps by using the field editor, or by using a temporary layout manager they create on the fly, or something else. I’m afraid I can’t help much with that, but someone else might be able to.
scraps schrieb am 18.12.2010
I have an NSTextField and I want to establish their contents if they click on a button and place your cursor over the text field at the end of the text so that if someone klicks the button that could start writing.
So far I use [NSTextField SelectText] selects the text field, it selects all the text so if someone just start typing the text would lose everything that alread is in the text field.
Jeena Paradies aus Varberg / Schweden schrieb am 18.12.2010
Have you tried to use setSelectedRange:?