I got a NSTokenField where I set the tokens via setObjectValue:[NSArray ..] with custom objects. I implement the general NSTokenFieldDelegate methods:
- (NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)_tokens atIndex:(NSUInteger)index
- (NSString *)tokenField:(NSTokenField *)tokenField displayStringForRepresentedObject:(id)representedObject
- (NSTokenStyle)tokenField:(NSTokenField *)tokenField styleForRepresentedObject:(id)representedObject
- (BOOL)tokenField:(NSTokenField *)tokenField hasMenuForRepresentedObject:(id)representedObject
- (NSMenu *)tokenField:(NSTokenField *)tokenField menuForRepresentedObject:(id)representedObject
- (BOOL)tokenField:(NSTokenField *)tokenField writeRepresentedObjects:(NSArray *)objects toPasteboard:(NSPasteboard *)pboard
- (NSArray *)tokenField:(NSTokenField *)tokenField readFromPasteboard:(NSPasteboard *)pboard
All seems to be working as I see the tokens in a not-editable textfield.
As it's a textfield (not editable), the user can select text (in this case tokens). When the user clicks on a token, it's marked as selected.
Now, I try to find out the selected token (after a mouse-down action) but it seems I'm unable to access this from the NSTokenField, nor the NSTextField nor NSControl.
I try to use the tokenField.selectedCell which is giving me NSTokenFieldCell: 0x6000001c2b20, an object not changing on my selection. When I ask the representedObject of the selectedCell, I got a null-reference.
Anyone got an idea how we can access the selected token from a NSTokenField?
The selection information is in the NSTokenField's associated cell's field editor. This code excerpt will print the tokens selected in self.tokenField
to the console:
NSArray *objects = [self.tokenField objectValue];
NSTextView *tv = [[self.tokenField cell] fieldEditorForView:self.tokenField];
NSArray *selections =[tv selectedRanges];
for (NSValue *rangeVal in selections) {
NSRange range = [rangeVal rangeValue];
for (NSUInteger i=0; i<range.length; i++) {
NSLog(@"%@", [objects objectAtIndex:range.location + i]);
}
}