Focus a NSTextField without selecting | 19. April 2009 um 12:52 Uhr / Programming

Eingestellt am 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 :-).


Kommentare

  Dein Kommentar 

Wie benutze ich BBcode?