显示没有焦点的NSPopover

时间:2014-01-16 03:25:46

标签: objective-c macos intellisense nspopover

我正在创建一个IntelliSense样式弹出窗口,显示在文本字段中键入哪些语法有效的用户。有没有人知道如何在不给予焦点的情况下显示NSPopover,以便用户可以继续输入textField?弹出窗口由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];
    }
}

2 个答案:

答案 0 :(得分: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];
    }
}

答案 1 :(得分:0)

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