防止空格键在自动填充文本字段中选择第一个建议

时间:2016-01-01 17:11:15

标签: objective-c macos cocoa

我已成功创建/修改/实施(有很多帮助)以下内容,以便从一系列建议中启用自动完成文本视图。它不区分大小写,效果很好!唯一的问题是空格键选择第一个建议,即使它不是我想要的那个......也就是说,当键入" Joe"我得到一个包括" Joe Client" "乔史密斯" "乔约翰史密斯"等...如果我按下空格键以试图进一步改进它(让我们说我想要" Joe John Smith")默认选择第一个建议" Joe Client&#34 ; :(

我想象有一种覆盖空间的方式,这样它就不会作为一个"进入"或" tab"但显然我不确定如何做到这一点......或类似于退格/删除键的处理方式......任何见解或建议都会非常有帮助。

提前致谢。

autocompleteController.h:

#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>

@interface autocompleteController : NSViewController< NSTextFieldDelegate, NSControlTextEditingDelegate>

@property (weak) IBOutlet NSTextField *textField;
@property (nonatomic) BOOL isAutocompleting;
@property (nonatomic, strong) NSString * lastEntry;
@property (nonatomic) BOOL backspaceKey;

-(IBAction)onEnter:(id)sender;
@end
@interface NSString (autocomplete)

- (BOOL)hasPrefixIgnoringCase:(NSString*)aString;
@end;

autocompleteController.M:

#import "autocompleteController.h"
#import "AddressBook/AddressBook.h"

@implementation autocompleteController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.textField.delegate = self;
}   
-(void)controlTextDidChange:(NSNotification *)obj{
    NSTextView * fieldEditor = [[obj userInfo] objectForKey:@"NSFieldEditor"];
    if (self.isAutocompleting == NO  && !self.backspaceKey) {
        self.isAutocompleting = YES;
        self.lastEntry = [[fieldEditor string] copy];
        [fieldEditor complete:nil];
        self.isAutocompleting = NO;
    }
    if (self.backspaceKey) {
        self.backspaceKey = NO;
    }
}   
-(NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index{
    NSMutableArray * suggestions = [NSMutableArray array];

    //A whole bunch of code to build the array of suggestions goes here- it's irrelevant to the question and long so in the name of brevity I've removed it...

    return suggestions;
}   
-(BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector{
    if (commandSelector == @selector(deleteBackward:)) {
        self.backspaceKey = YES;
    }
    return NO;
}
@end  
@implementation NSString (autocomplete)    
- (BOOL)hasPrefixIgnoringCase:(NSString*)aString
{
    NSRange prefix = [self rangeOfString:aString options:NSCaseInsensitiveSearch];
    return prefix.location == 0 && prefix.length == aString.length;
}
@end

0 个答案:

没有答案