如何为NSTextField的NSFieldEditor设置自动补全候选字典?
为NSTextField指定自动补全词汇的实现方法
要给你的NSTextField指定自定义自动补全词汇(基于你已有的NSArray),需要通过NSTextFieldDelegate的代理方法提供补全列表,具体步骤如下:
让控制器遵循NSTextFieldDelegate协议
在控制器的类扩展或头文件中声明协议:@interface YourViewController () <NSTextFieldDelegate> @property (nonatomic, strong) NSArray *completionWords; // 存储你的自定义补全词汇数组 @property (nonatomic, copy) NSString *lastTypedStreetValue; @end绑定NSTextField的代理
确保目标NSTextField的delegate指向当前控制器,可通过代码设置:// 在viewDidLoad或初始化方法中 self.yourTextField.delegate = self; // 初始化补全词汇数组(替换为你自己的数组) self.completionWords = @[@"Maple Street", @"Oak Avenue", @"Pine Road", @"Cedar Lane"];实现补全代理方法
实现control:textView:completions:forPartialWordRange:indexOfSelectedItem:方法,该方法会在调用[fieldEditor complete:nil]时触发,返回匹配当前输入的补全列表:- (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index { // 获取当前输入的待补全文本片段 NSString *currentInput = [textView.string substringWithRange:charRange]; // 过滤出匹配的补全词汇(这里用不区分大小写的前缀匹配) NSPredicate *matchPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", currentInput]; NSArray *matchedCompletions = [self.completionWords filteredArrayUsingPredicate:matchPredicate]; // 返回过滤后的补全列表 return matchedCompletions; }保留原有输入监听逻辑
你之前编写的controlTextDidChange:方法可以继续使用,它负责在文本变化时触发补全弹窗:-(void)controlTextDidChange:(NSNotification *)notification { NSTextView *fieldEditor = [[notification userInfo] objectForKey:@"NSFieldEditor"]; NSString *newValue = [fieldEditor string]; BOOL textDidNotChange = [lastTypedStreetValue isEqualToString:newValue]; if( textDidNotChange ){ return; } else { lastTypedStreetValue = [newValue copy]; [fieldEditor complete:nil]; } }
可选调整
- 如果需要模糊匹配(只要词汇包含当前输入即可),可将过滤条件中的
BEGINSWITH[c]替换为CONTAINS[c]; indexOfSelectedItem参数可设置默认选中的补全项索引,无需默认选中时传入NULL或设为-1即可。
内容的提问来源于stack exchange,提问作者murkr
相关产品推荐
相关产品推荐

