NSTokenField: different colors for tokens

被刻印的时光 ゝ 提交于 2021-02-08 05:19:13

问题


I have created an NSTokenField in my xib. I'd like to display tokens with different colors inside that tokenField. Meaning: some tokens will be blue, the rest will be red (according to their content). Is that possible?

The following code doesn't work for me. I hope someone can help me out:

- (id)tokenField:(NSTokenField *)tokenField representedObjectForEditingString:(NSString *)editingString
{
    id returnRepresentedObject = nil;

    NSTokenFieldCell *tf = [[NSTokenFieldCell alloc] init];
    tf.stringValue = editingString;
    tf.backgroundColor = [NSColor redColor];
    returnRepresentedObject = tf;

    return returnRepresentedObject;
}

Result: all tokens remain blue... :-(

Any help will be highly appreciated!


回答1:


Its possible by using private APIs. Subclass NSTokenAttachmentCell (Private) and NSTokenFieldCell.

Sample project

enter image description here

Use BWTokenAttachmentCell and BWTokenFieldCell class and NSTokenAttachmentCell class dump from BWToolkit. Modify initialize method of BWTokenAttachmentCell.

[sample project

NOTE:

Use this method if you are not targeting for Mac App Store.




回答2:


You'll probably have to role your own. There is a wwdc video from 2010 about advanced Cocoa Text handling. The NSTokenField Uses NSTextAttachments to render the tokens.



来源:https://stackoverflow.com/questions/17672413/nstokenfield-different-colors-for-tokens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!