1

我有一个将令牌添加到 NSTokenField 的按钮。它总是将令牌添加到字段的末尾:

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;

因为它是从 currentField objectValue 中抓取数组,然后通过添加对象来创建数组。

我想让它知道光标的插入点并将对象插入到生成的 currentField objectValue 中,这样我就可以使用正确排序的标记设置 currentField 的 ObjectValue。谢谢大家的帮助

4

1 回答 1

2

所以我想通了,我想我会分享我的解决方案。

需要抓住 fieldEditor 并检查其 selectedRange。

NSText *textEditor = [currentField currentEditor];

这将为您提供当前编辑的文本字段中的插入点。但是,如果您有一个将文本和标记混合在一起的 tokenField,那么您会发现每个标记仅计为 selectedRange 中的一个字符。

如果是这种情况,那么您需要编写一些逻辑以正确插入 currentField 数组。

  1. 脚步:
    1. 制作一个临时 NSMutableArray
    2. 用 [currentField objectValue] 填充它
    3. 遍历这个临时数组,增加一个位置计数器,1 表示种类标记的类,1 表示非标记字符串中的每个字符
    4. 在每个循环结束时增加你的数组索引
    5. 确保检查 positioncounter 是否等于或大于您的 [currentFieldEditor selectedRange].location 并跳出循环
    6. 最后将新令牌插入临时数组,然后 [currentField setObjectValue: with that array]

我的标记用逗号分隔,并以 $token$ 样式名称塞入 NSDictionaries 这就是我在运行循环时在文本和标记之间划定的方式。

快乐的 :)

于 2010-07-30T18:28:09.843 回答