AppendAttributedString: in NSMutableAttributedString

I have an MSMutableAttributedString displayContent. Content attributes vary in lines, that is, the colors and font sizes may vary depending on the letter.

I want to add a new character to the end of the line and get the attributes of the last character in displayContent for this. I can’t know what these attributes are in advance, since they are under user control.

When I add a new character (tempAttr):

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

it shows the reset attributes of the entire string to the attributes of the new character (which I did not specify, since I cannot know what they need).

How do I get tempAttr to display the attributes of the last character in displayContent? Thank.


Update Progress in this was awkward, but functional. Copy the attribute dictionary from the last character on the display (displayContent), and then reapply these attributes to the new character to be added:

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

I would hope that there is a more elegant way to do this, for example, by setting the NSTextField property.

+5
source share
1 answer

I think I accidentally discovered this solution, and then found this page, looking for the answer to the problem that I created for myself (the opposite of your problem).

If you do the following:

[[displayContent mutableString] appendString:newCharacter];

In the end, you add newCharacter, and the previous attributes are β€œstretched” to close it. However, I cannot find this behavior anywhere, so you may have nothing to count on it.

+15

All Articles