NSTokenField
動作選擇器在創建新標籤時不會被調用。根據您在界面生成器中進行的設置,您可以在按Enter鍵結束編輯時調用它(發送僅輸入),或者當您以其他方式結束編輯時(發送結束編輯) 。爲了得到良好的控制,你需要另一種方法。
出現時tokenising字符添加到令牌場藍色標籤被稱爲文本附件(的NSTextAttachment
實例)。處理標記添加/刪除標記字段時的一種方法是跟蹤包含在標記字段的基礎屬性字符串中的這些對象數量的變化。
要訪問相關的屬性字符串,您需要掌握fieldEditor的layoutManager
- 最終提供出現在文本視圖中的字符串的對象。一旦掌握了該信息,每次收到controlTextDidChange:
消息時,請計算其attributedString
的string
表示中的文本附件數。如果這次的數字大於先前計數中記錄的數字,則會添加標籤。
#import "AppDelegate.h"
@interface AppDelegate()
@property (weak) IBOutlet NSWindow *window;
@property (weak) NSLayoutManager *lm;
@property (nonatomic) NSUInteger tokenCount;
@end
@implementation AppDelegate
// The text in the fieldEditor has changed. If the number of attachments in the
// layoutManager's attributedString has changed, either a new tag has been added,
// or an existing tag has been deleted.
-(void)controlTextDidChange:(NSNotification *)obj {
NSUInteger updatedCount = [self countAttachmentsInAttributedString:self.lm.attributedString];
if (updatedCount > self.tokenCount) {
NSLog(@"ADDED");
self.tokenCount = updatedCount;
} else if (updatedCount < self.tokenCount) {
NSLog(@"REMOVED");
self.tokenCount = updatedCount;
}
}
// About to start editing - get access to the fieldEditor's layoutManager
-(BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor {
self.lm = [(NSTextView *)fieldEditor layoutManager];
return YES;
}
// Iterate through the characters in an attributed string looking for occurrences of
// the NSAttachmentCharacter.
- (NSInteger)countAttachmentsInAttributedString:(NSAttributedString *)attributedString {
NSString *string = [attributedString string];
NSUInteger maxIndex = string.length - 1;
NSUInteger counter = 0;
for (int i = 0; i < maxIndex + 1; i++) {
if ([string characterAtIndex:i] == NSAttachmentCharacter) {
counter++;
}
}
return counter;
}
@end
你可以看看下面的帖子: http://stackoverflow.com/questions/852038/delegate-methods-of-nstextfield-using-nsnotification – 2015-02-09 13:22:48
@DavidMangon謝謝。不幸的是,它不是一個完整的解決方案,因爲我需要檢測何時添加新的令牌。 ' - (void)textDidChange:(NSNotification *)aNotification'在輸入字符時以及添加標記字符時調用。 stringValue不會顯示添加的標記化字符,並且通知是相同的。 – 2015-02-09 17:22:42