我有一个 MSMutableAttributedString 显示内容。内容的属性因字符串而异,即颜色和字体大小可能因字母而异。
我想在字符串的末尾添加一个新字符,并让它获取 displayContent 中最后一个字符的属性。我无法提前知道这些属性是什么,因为它们在用户控制之下。
当我附加新字符(tempAttr)时:
NSAttributedString * tempAttr = [[NSAttributedString alloc] initWithString:appendage];
[displayContent appendAttributedString:tempAttr];
它似乎将整个字符串的属性重置为新字符的属性(我没有设置,因为我不知道它们需要什么)。
如何让 tempAttr 获取 displayContent 中最后一个字符的属性?谢谢。
更新。以笨拙但实用的方式在这方面取得了进展。从显示中的最后一个字符 (displayContent) 复制属性字典,然后将这些属性重新应用到要添加的新字符:
NSMutableDictionary * lastCharAttrs = [NSMutableDictionary dictionaryWithCapacity:5];
[lastCharAttrs addEntriesFromDictionary: [displayContent attributesAtIndex:0
effectiveRange:NULL]]; // get style of last letter
NSMutableAttributedString * tempAttr = [[NSMutableAttributedString alloc] initWithString:newCharacter
attributes:lastCharAttrs];
[displayContent appendAttributedString:tempAttr]; // Append to content in the display field
我希望有一种更优雅的方法来做到这一点,比如设置 NSTextField 的属性。