objective-c 聚焦一个 NSTextField

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/764179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:25:24  来源:igfitidea点击:

focus a NSTextField

objective-ccocoa

提问by Jeena

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.

我有一个 NSTextField,如果我点击一个按钮,我想设置它的内容,然后将光标设置在文本末尾的这个文本字段上,这样如果有人点击按钮,他就可以开始输入。

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.

到目前为止,我使用 [NSTextField selectText] 它选择这个文本字段,但它选择整个文本,所以如果有人刚开始输入,他会丢失文本字段中已经存在的所有文本。

回答by ewcy

or even easier

甚至更容易

[yourTextField becomeFirstResponder];

回答by Jeena

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:

在 RubyCocoa 中,它是:

def select_input_field
    @input.selectText self
    range = OSX::NSRange.new(@input.stringValue.length, 0)
    @input.currentEditor.setSelectedRange range
end

回答by macinjosh

You'll want to do something like this:

你会想要做这样的事情:

[[self window] makeFirstResponder:[self yourTextField]];

回答by Antwan van Houdt

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

这可以完成工作:)

回答by vasylz

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

前段时间我做了类似的任务。我的解决方案是写下 NSTextField 部分文本选择的小类别方法。这个方法的工作就像原来的 selectText: 一样(设置焦点来控制)。

@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.

使用此方法,您可以将文本选择放在您想要的位置,然后立即开始输入。