appendAttributedString:在NSMutableAttributedString中

Lia*_*m G 5 objective-c nsattributedstring

我有一个MSMutableAttributedString displayContent.内容的属性在字符串中有所不同,即颜色和字体大小可能因字母而异.

我想在字符串的末尾添加一个新字符,并让它获取displayContent中最后一个字符的属性.由于用户无法控制,我无法预先知道这些属性是什么.

当我追加新角色(tempAttr)时:

NSAttributedString * tempAttr = [[NSAttributedString alloc] initWithString:appendage];
[displayContent appendAttributedString:tempAttr];
Run Code Online (Sandbox Code Playgroud)

它似乎将整个字符串的属性重置为新字符的属性(我没有设置,因为我不知道它们需要什么).

如何让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
Run Code Online (Sandbox Code Playgroud)

我希望有一个更优雅的方法来设置NSTextField的属性.

Ben*_*ran 15

我想我偶然发现了一个解决方案,然后在寻找我为自己创建的问题的答案时找到了这个页面(与你的问题相反).

如果您执行以下操作:

[[displayContent mutableString] appendString:newCharacter];
Run Code Online (Sandbox Code Playgroud)

您将最终使用newCharacter追加和之前的属性"拉伸"来覆盖它.但是,我无法在任何地方找到此行为,因此您可能会厌倦指望它.