How to make NSSearchField send action upon autocompletion?

后端 未结 1 1574
鱼传尺愫
鱼传尺愫 2020-12-18 03:50

This question seems straightforward but I\'ve tried everything I can think of, and Googled for hours.

I have an NSSearchField that does autocomplete, basically copyi

相关标签:
1条回答
  • 2020-12-18 04:17

    I figured out how to make this work.

    You need to override the NSFieldEditor for the NSTextViews.

    To provide an overridden version, in the NSWindow's delegate:

    - (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client
    {
        if ([client isKindOfClass:[NSSearchField class]])
        {
            if (!_mlFieldEditor)
            {
                _mlFieldEditor = [[MLFieldEditor alloc] init];
                [_mlFieldEditor setFieldEditor:YES];
            }
            return _mlFieldEditor;
        }
        return nil;
    }
    

    _mlFieldEditor is an instance variable. Here is the definition:

    @interface MLFieldEditor : NSTextView
    @end
    
    @implementation MLFieldEditor
    
    
    -  (void)insertCompletion:(NSString *)word forPartialWordRange:(NSRange)charRange movement:(NSInteger)movement isFinal:(BOOL)flag
    {
        // suppress completion if user types a space
        if (movement == NSRightTextMovement) return;
    
        // show full replacements
        if (charRange.location != 0) {
            charRange.length += charRange.location;
            charRange.location = 0;
        }
    
        [super insertCompletion:word forPartialWordRange:charRange movement:movement isFinal:flag];
    
        if (movement == NSReturnTextMovement)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:MLSearchFieldAutocompleted object:self userInfo:nil];
        }
    }
    
    @end
    

    The key part is the NSReturnTextMovement after the [super insertCompletion...].

    The first part will change it so that typing the space key won't perform autocompletion, which was a comment I had made on: How to prevent NSSearchField from overwriting entered strings using the first autocompletion list entry?

    0 讨论(0)
提交回复
热议问题