nin*_*rew 4 macos objective-c nstextfield deselect
在开发一个新应用程序时,我遇到了这里描述的相同问题,在取消选择输入到 nstextfield 中的文本时遇到了同样的问题:http : //www.cocoabuilder.com/archive/cocoa/195313-nstextfield-how-to-取消选择-text.html
关于使用 NSTextViews 执行此操作有很多问题,但我无法为 NSTextFields 找到有效的答案。
在我的项目中,我有一个带有文本字段的窗口,其中包含一个控制器类,该类也是文本字段的委托。我有一个 IBAction 用于在输入时发送的文本字段,它根据字段中的文本执行操作,以及:
(void)controlTextDidChange:(NSNotification *)note
Run Code Online (Sandbox Code Playgroud)
和
(BOOL)control:(NSControl *)control
textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
Run Code Online (Sandbox Code Playgroud)
它处理一些自定义的自动完成,如在Suppressing the text completion dropdown for an NSTextField的答案中
我的问题在于当我按 Enter 提交输入的文本时,字段中的字符串被完全选中,但我希望能够取消选择文本并在末尾添加插入点,如第一个链接中所述。
有多个地方我可以让它取消选择文本,但实际上取消选择不起作用。我已经尝试获取第一个链接中描述的字段编辑器,我也尝试使用 controlTextDidEndEditing: 方法,因为我确实在上面的 controlTextDidChange: 方法中获得了一个字段编辑器:
- (void)controlTextDidEndEditing:(NSNotification *)note{
NSTextView *textView = [[note userInfo] objectForKey:@"NSFieldEditor"];
[textView setSelectedRange:NSMakeRange([[self.ParseField stringValue]length]-1, 0)
affinity:NSSelectionAffinityUpstream
stillSelecting:NO];
}
Run Code Online (Sandbox Code Playgroud)
我还尝试在现场禁用和重新启用编辑,但这也不起作用。
像能够向文本字段发送 moveDown: 消息一样简单的事情对我有用,因为它与点击向下箭头相同,但文本字段无法识别该选择器。(我认为 NSTextField 继承自 NSResponder,所以它会起作用,但我猜不是?)
感谢您的任何帮助
在一个只有一个窗口和文本字段的简单应用程序中。
我将 textField 设置为 firstResponder。
这使得在应用程序运行时选择文本。

如果我添加到applicationDidFinishLaunching
NSRange tRange = [[ _theTextField currentEditor] selectedRange];
[[ _theTextField currentEditor] setSelectedRange:NSMakeRange(tRange.length,0)];
现在,当运行时,文本未被选中,插入点位于文本的末尾。

我使用selectedRange 来获取选择字符长度。由于文本是首先被选中的,看起来更简单。
- (void)awakeFromNib{
[_theTextField setStringValue:@"100000"];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[[[NSApplication sharedApplication] mainWindow] makeFirstResponder:_theTextField];
NSRange tRange = [[ _theTextField currentEditor] selectedRange];
[[ _theTextField currentEditor] setSelectedRange:NSMakeRange(tRange.length,0)];
Run Code Online (Sandbox Code Playgroud)
}
我一直在 Swift 3 中寻找解决方案,所以这对我有用:
theTextField.currentEditor()?.selectedRange = NSMakeRange(0, 0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3377 次 |
| 最近记录: |