views:

32

answers:

1

I have a button that adds a token to a NSTokenField. It adds the token always to the end of the field:

NSTokenField *currentField = [sender representedObject];

    // Determine which token should be inserted into the field using the tag of the sender.
    switch( [sender tag] )
    {
        case eFileNameToken_StartDate:
            [currentField setObjectValue:[[currentField objectValue] arrayByAddingObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:kTokenName_StartDate, kTokenKey_Name, @"%m-%d-%Y", kTokenKey_Format, [NSNumber numberWithInt:0], kTokenKey_FormatIndex, nil]]];
            break;

Because it is grabbing the array from the currentField objectValue and then creating an array by adding the object.

I would love to have it know the insertion point of the cursor and insert the object into the resulting currentField objectValue so that I can then setObjectValue of the currentField with the correctly ordered tokens. Thanks for any help yall

+1  A: 

So I figured it out and I thought Id share my solution.

One needs to grab the fieldEditor and check its selectedRange.

NSText *textEditor = [currentField currentEditor];

This gives you the insertion point in the currently edited text field. However if you have a tokenField that has text and tokens mixed together then you will find that each token only counts as one character in the selectedRange.

If this is the case then you need to write some logic to correctly insert into the currentField array.

  1. Steps:
    1. make a temp NSMutableArray
    2. fill that with the [currentField objectValue]
    3. iterate through this temp array, incrementing a postion counter, 1 for classes of kind token, 1 for each character in a non token string
    4. at the end of each loop increment your array index
    5. make sure to check if the positioncounter is equal or greater than your [currentFieldEditor selectedRange].location and break out of the loop
    6. Finally insert your new token into the temp array and then [currentField setObjectValue: with that array]

My tokens are comma delinated and shoved into NSDictionaries with $token$ style names This is how I delineate between text and tokens when I run my loop.

happy :)

theprojectabot