开发者

appendAttributedString: in NSMutableAttributedString

I have an MSMutableAttributedString displayContent. The attributes of the content vary across the string i.e. the colours and font sizes can vary by letter.

I want to add a new character to the end of the string and for it to pick up the attributes of the last character in displayContent. I cannot know what those attributes are in advance since they are under user control.

When I append the new character (tempAttr):

NSAttributedString * tempAttr = [[NSAttributedString alloc] initWithString:appendage];
[displayContent appendAttributedString:tempAttr];

it appears to reset the attributes of the whole string to the attributes of the new character (which I haven't set since I can't know what they need to be).

How do I get tempAttr to pick up the attributes of the last character in displayContent? Thanks.


Update. Made progress on this in a clumsy but functional way. Copy the attributes dictionary from the last character in the display (displayContent) and then reapply those attributes to the new character being added:

NSMutableDictionary * last开发者_开发知识库CharAttrs = [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

I would have hoped there was a more elegant way to do this like setting a property of the NSTextField.


I think I discovered a solution to this by accident, then found this page while looking for the answer to the problem I created for myself (the opposite of your issue).

If you do the following:

[[displayContent mutableString] appendString:newCharacter];

You'll end up with newCharacter appended and the previous attributes "stretched" to cover it. I cannot find this behavior documented anywhere, however, so you might be weary of counting on it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜