0

我正在创建一个 IntelliSense 样式的弹出框,它向正在输入文本字段的用户显示什么语法是有效的。有谁知道如何在不给它焦点的情况下显示 NSPopover,以便用户可以继续输入文本字段?弹出框由 controlTextDidChange 触发:

- (void) controlTextDidChange:(NSNotification *)obj
{

    NSTextField *field = [obj object];
    NSString *command = [field stringValue];

    if ([[command substringFromIndex: command.length - 1] isEqualToString: @"#"]){
        CompletionMenuController *completionController = [[CompletionMenuController alloc] initWithNibName: @"CompletionMenuController" bundle:[NSBundle mainBundle]];
        completionMenuPopover = [[NSPopoverInformation alloc] init];
        [completionMenuPopover setContentViewController: completionController];
        [completionMenuPopover setContentSize: completionController.view.frame.size];
        [completionMenuPopover setBehavior: NSPopoverBehaviorTransient];
        [completionMenuPopover setAppearance: NSPopoverAppearanceHUD];
        [completionMenuPopover showRelativeToRect:[_commandBar frame] ofView:_commandBar preferredEdge:NSMaxYEdge];
    }
}
4

2 回答 2

1

NSPopover 的自动关闭似乎取决于检测焦点变化。这意味着如果它是瞬态的,则需要将第一响应者状态设置为弹出框。试试看NSPopoverBehaviorApplicationDefined是否能解决焦点问题。但是,您必须小心关闭弹出窗口。但是,如果没有其他方法,将焦点显式设置回编辑控件也是一种可能的选择。显示弹出框不会改变视觉外观,因此该短焦点开关不会闪烁。

于 2014-01-16T08:50:11.913 回答
1

这是一种解决方法,不完全是我尝试完成此操作的方式,但它确实有效。在打开弹出框之前,我将光标位置保存在文本字段中,然后给文本字段第一响应者并将光标位置更改回原来的位置。

if ([_commandBar stringValue].length > 0){
    NSString *command   = [_commandBar stringValue];
    NSRange range       = [[_commandBar currentEditor] selectedRange];

    //Open popover if command is being typed
    if ([[command substringFromIndex: command.length - 1] isEqualToString: @"#"]){
        CompletionMenuController *completionController = [[CompletionMenuController alloc] initWithNibName: @"CompletionMenuController" bundle:[NSBundle mainBundle]];

        //Configure and Open Popover
        if ([completionMenuPopover isShown]) [completionMenuPopover close];
        completionMenuPopover = [[NSPopover alloc] init];
        [completionMenuPopover setContentViewController: completionController];
        [completionMenuPopover setContentSize: completionController.view.frame.size];
        [completionMenuPopover setBehavior: NSPopoverBehaviorTransient];
        [completionMenuPopover setAppearance: NSPopoverAppearanceHUD];
        [completionMenuPopover setAnimates: NO];
        [completionMenuPopover showRelativeToRect:[_commandBar frame] ofView:_commandBar preferredEdge:NSMaxYEdge];

        //Reset Command Bar as First Responder
        [_commandBar becomeFirstResponder];
        [[_commandBar currentEditor] setSelectedRange: range];
    }
}
于 2014-01-16T19:27:58.173 回答