我已經嘗試了一個基於文檔的使用ARC的應用程序,使我的Document類成爲NSTokenFieldDelegate的NSTokenField的簡單第一個示例。它的工作原理是:委託方法tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:即使我成功編輯了不是標記字符串中第一個標記的標記,它也從不會看到indexOfToken爲0的任何內容。我在OS X 10.8.2上使用10.8框架的XCode 4.5。NSTokenField的tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:indexOfToken始終爲零
問題:爲什麼總是0?我期望它是由用戶編輯的字段中間接看到的令牌0..n-1中的令牌的索引。
要重現,啓動一個項目的上方和下方添加文本,然後使用XIB編輯器並拖動NSTokenField到文檔窗口,設置令牌字段作爲文檔的tokenField,使文檔實例令牌的代表領域。
Document.h:
#import <Cocoa/Cocoa.h>
@interface Document : NSDocument <NSTokenFieldDelegate>
{
IBOutlet NSTokenField *tokenField; // of (Token *).
NSMutableDictionary *tokens; // of (Token *).
}
@end
Token.h:
#import <Foundation/Foundation.h>
@interface Token : NSObject
@property (strong, nonatomic) NSString *spelling;
- (id)initWithSpelling:(NSString *)s;
@end
Token.m:
#import "Token.h"
@implementation Token
@synthesize spelling;
- (id)initWithSpelling:(NSString *)s
{
self = [super init];
if (self)
spelling = s;
return self;
}
@end
Document.m:令牌
#import "Document.h"
#import "Token.h"
@implementation Document
- (id)init
{
self = [super init];
if (self) {
tokens = [NSMutableDictionary dictionary];
}
return self;
}
...
#pragma mark NSTokenFieldDelegate methods
- (NSArray *)tokenField:(NSTokenField *)tokenField
completionsForSubstring:(NSString *)substring
indexOfToken:(NSInteger)tokenIndex
indexOfSelectedItem:(NSInteger *)selectedIndex
{
NSLog(@"tokenField:completionsForSubstring:\"%@\" indexOfToken:%ld indexOfSelectedItem:",
substring, tokenIndex);
NSMutableArray *result = [NSMutableArray array];
for (NSString *key in tokens) {
//NSLog(@"match? \"%@\"", key);
if ([key hasPrefix:substring])
[result addObject:key];
}
return result;
}
- (id)tokenField:(NSTokenField *)tokenField representedObjectForEditingString:(NSString *)editingString
{
NSLog(@"tokenField:representedObjectForEditingString:\"%@\"", editingString);
Token *token;
if ((token = [tokens objectForKey:editingString]) == nil) {
token = [[Token alloc] initWithSpelling:editingString];
[tokens setObject:token forKey:editingString];
//NSLog(@"token %@", [token description]);
NSLog(@"tokens %@", [tokens description]);
}
return token;
}
- (NSString *)tokenField:(NSTokenField *)tokenField displayStringForRepresentedObject:(id)representedObject
{
NSString *spelling = [representedObject spelling];
NSLog(@"tokenField:displayStringForRepresentedObject: = \"%@\"", spelling);
return spelling;
}
@end
條目被終止以換行或逗號字符。
這似乎仍然是一個問題。我想知道爲什麼它尚未修復。 – adev
我解決了這個問題,稍後會發布答案。 – adev
發表我的工作答案在這裏迅速https://stackoverflow.com/a/45311580/8234523 – adev