Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus a NSTextField

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.

like image 544
Jeena Avatar asked Apr 18 '09 20:04

Jeena


5 Answers

or even easier

[yourTextField becomeFirstResponder];
like image 74
ewcy Avatar answered Nov 18 '22 06:11

ewcy


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
like image 39
Jeena Avatar answered Nov 18 '22 07:11

Jeena


You'll want to do something like this:

[[self window] makeFirstResponder:[self yourTextField]];
like image 31
joshwbrick Avatar answered Nov 18 '22 07:11

joshwbrick


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 :)

like image 22
Antwan van Houdt Avatar answered Nov 18 '22 05:11

Antwan van Houdt


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.

like image 2
vasylz Avatar answered Nov 18 '22 05:11

vasylz