質問

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.

enter image description here

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.

enter image description here

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]);
    }
}

他のヒント

Rather than using mouseDown(_:) I found it better to use the NSTextField delegate method textViewDidChangeSelection.

Heres the code in Swift.

public func textViewDidChangeSelection(notification: NSNotification) {

    if let fieldView = tokenField.cell!.fieldEditorForView(self) {

        var selectedObjects = [AnyObject]()

        for value in fieldView.selectedRanges {    
            let range = value.rangeValue

            for var i = 0 ; i < range.length ; i++ {
                selectedObjects.append(tokenField.objectValue!.objectAtIndex(range.location + i))
            }
        }
        Swift.print("selected objects:\(selectedObjects)")
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top