15

在 Mail 的NSTokenField中输入无效电子邮件时,会得到以下信息(令牌纯字符串值的混合):

替代文字

有什么可推荐的方法来实现这一点吗?
NSTokenField 甚至是正确的工具吗?还是我会滥用它?

在这个特定的项目中,我需要允许用户输入文件名模式
(尽管还有其他几个用例),并支持预定义的令牌。

现在我需要像这样输入输入:

Glue Text %[Tag]Other Glue Text%[Another Tag]More Text

我想把它改成这样的一些万无一失的图形解决方案: 替代文字

NSTokenField always(!) 将输入的文本转换为标记。

要么我在网络搜索中使用了错误的关键字,
要么我真的是第一个需要这种(混合)行为的人?!

我确实阅读了 Apple 的 NSTokenField 指南,但找不到任何关于我的问题的信息。

4

2 回答 2

12

您需要实现委托方法tokenField:styleForRepresentedObject:以返回NSRoundedTokenStyle令牌或NSPlainTextTokenStyle其他文本。令牌的表示对象是令牌字符串本身,除非您的委托返回其他对象。

这应该可以解决您的问题:

- (NSTokenStyle)tokenField:(NSTokenField *)tokenField
 styleForRepresentedObject:(id)representedObject
{
    if ([representedObject rangeOfString: @"%["].location == 0) {
        return NSRoundedTokenStyle;
    } else {
        return NSPlainTextTokenStyle;
    }
}
于 2010-11-22T12:19:14.633 回答
2

Actually, you first have to define a tokenizing character, which in your case would be %

[tokenField setTokenizingCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"%%"]];

The input string needs to changed as well into:

Glue Text %[Tag]%Other Glue Text%[Another Tag]%More Text

... so that Cocoa knows where the token ends.

And if you want [Tag] to be displayed as Tag in the token field, you also need to implement the tokenField:displayStringForRepresentedObject: method:

- (NSTokenStyle)tokenField:(NSTokenField *)tokenField
 displayStringForRepresentedObject:(id)representedObject
{
    if ([representedObject rangeOfString: @"["].location == 0) {
        return [(NSString*)representedObject substringWithRange:NSMakeRange(1, [(NSString*)representedObject length]-2)];

    return representedObject;
}

However, this has a big drawback : if you copy or just move a token, Cocoa will call tokenField:displayStringForRepresentedObject: and the copied/moved token will be changed to regular text Tag instead of the token [Tag].

If someone has a solution to the above problem, I'd be happy to read it.

于 2011-05-19T14:18:02.897 回答