我有一个按钮,可以将 token 添加到 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。 感谢大家的帮助
最佳答案
所以我想通了,我想我应该分享我的解决方案。
需要获取 fieldEditor 并检查其 selectedRange。
NSText *textEditor = [currentField currentEditor];
这将为您提供当前编辑的文本字段中的插入点。但是,如果您有一个将文本和标记混合在一起的 tokenField,那么您会发现每个标记仅算作 selectedRange 中的一个字符。
如果是这种情况,那么您需要编写一些逻辑来正确插入到 currentField 数组中。
- 步骤:
- 创建一个临时 NSMutableArray
- 用 [currentField objectValue] 填充该值
- 迭代此临时数组,递增位置计数器 1 对于种类标记的类别,1 表示 非标记字符串中的每个字符
- 在每个循环结束时增加数组索引
- 确保检查位置计数器是否等于或大于 比你的 [currentFieldEditor selectedRange].location 并中断 跳出循环
- 最后将新 token 插入临时数组中,然后 [currentField setObjectValue: 与 该数组]
我的 token 以逗号分隔并以 $token$ 样式名称插入 NSDictionaries 中 这就是我在运行循环时划分文本和标记的方式。
开心:)
关于cocoa - 我想在光标的插入点插入标记,而不是数组的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3349065/