Jeremy Smith
Jeremy Smith

Reputation: 15069

How do I force the cursor to the end of a NSTextField?

I am NSOpenPanel to select a file or folder from a user's machine. But when the user clicks "open" the cursor is at the beginning of the path that shows up in the text field. This is a problem because until you click in the textfield and arrow right, you won't see that the entire path is listed. For example if the path is:

/Users/jeremysmith/code/testfolder/testfolder2

It may only show:

/Users/jeremysmith/code/

since the cursor is at the beginning and the text field's width only goes to "code".

Upvotes: 14

Views: 7440

Answers (4)

Andrew Aarestad
Andrew Aarestad

Reputation: 1160

Here's my Swift solution:

self.fileTextField.currentEditor()?.moveToEndOfDocument(nil)

Upvotes: 6

Dan Rosenstark
Dan Rosenstark

Reputation: 69757

In Swift, since it's 2015:

self.textField.moveToEndOfDocument(nil)

Upvotes: 4

simon.d
simon.d

Reputation: 2531

I got this working on textfields by doing:

[[self.inputFileTextField currentEditor] moveToEndOfLine:nil];

Upvotes: 27

jscs
jscs

Reputation: 64002

Two ideas spring to mind. First, you could use -[NSTextView setSelectedRange:]:

NSTextView * fieldEditor = [thePanel fieldEditor:NO forObject:theTextField];

NSUInteger text_len = [[fieldEditor string] length];

[fieldEditor setSelectedRange:(NSRange){text_len, 0}];

Or you could use one of the NSResponder action methods on the text field, like moveDown:, moveToEndOfLine:, moveToEndOfParagraph:, &c. Faking a "Page Down" or "Down Arrow" keypress with [theTextField keyDown:...] might also work.

Upvotes: 2

Related Questions