21

I have a NSTextField and I want to set its content if I klick on a button and than set the cursor on this textfield at the end of the text so if someone klicks the button he could just begin to type.

Until now I use [NSTextField selectText] it selects this textfield but it selects the whole text so if someone just begins to type he'd lose all the text which alread is in the textfield.

Jeena
  • 2,172
  • 3
  • 27
  • 46

5 Answers5

34

or even easier

[yourTextField becomeFirstResponder];
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
ewcy
  • 405
  • 1
  • 4
  • 3
  • The problem with that is that this selects all the text and if you begin to type the prepopulated text will be overwritten, I wanted to set the cursor behind the text. – Jeena Nov 08 '11 at 21:11
  • 17
    This method is deprecated in 10.5, furthermore, if you read the documentation for this method it quite clearly states 'Never invoke this method directly.' – Alan Rogers Nov 29 '11 at 23:52
  • 2
    Good point, Alan, I've just removed a bunch of calls that were raising an exception for using becomeFirstResponder directly, using the 10.8 SDK. – Pablo D. Oct 12 '12 at 18:02
22

Ok I found it out now :)

- (IBAction)focusInputField:(id)sender {
    [textField selectText:self];
    [[textField currentEditor] setSelectedRange:NSMakeRange([[textField stringValue] length], 0)];  
}

and in RubyCocoa it is:

def select_input_field
    @input.selectText self
    range = OSX::NSRange.new(@input.stringValue.length, 0)
    @input.currentEditor.setSelectedRange range
end
Jeena
  • 2,172
  • 3
  • 27
  • 46
11

You'll want to do something like this:

[[self window] makeFirstResponder:[self yourTextField]];
pkamb
  • 33,281
  • 23
  • 160
  • 191
joshwbrick
  • 5,882
  • 9
  • 48
  • 72
3

I am writing an ingame plugini, I were having a similar problem:

- (void)gotEvent:(NSEvent *)newEvent
{
  [mainWindow makeKeyAndOrderFront:self];
  [mainWindow makeFirstResponder:messageField];
  [mainWindow sendEvent:newEvent]; // will forward the typing event
}

this does the job :)

Antwan van Houdt
  • 6,989
  • 1
  • 29
  • 52
2

Some time ago I did similar task. My solution was write down small category method for partial text selection for NSTextField. This method does job like original selectText: does (with setting focus to control).

@implementation NSTextField( SelExt )

-(void)selectTextRange:(NSRange)range
{
   NSText *textEditor = [self.window fieldEditor:YES forObject:self];
   if( textEditor ){
      id cell = [self selectedCell];
      [cell selectWithFrame:[self bounds] inView:self 
            editor:textEditor delegate:self
            start:range.location length:range.length];
   }
}

@end

with this method you may place text selection where you want and start typing right after that.

vasylz
  • 177
  • 1
  • 4