Search code examples
iosnsattributedstring

How can I concatenate NSAttributedStrings?


I need to search some strings and set some attributes prior to merging the strings, so having NSStrings -> Concatenate them -> Make NSAttributedString is not an option, is there any way to concatenate attributedString to another attributedString?


Solution

  • I'd recommend you use a single mutable attributed string a @Linuxios suggested, and here's another example of that:

    NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] init];
    
    NSString *plainString = // ...
    NSDictionary *attributes = // ... a dictionary with your attributes.
    NSAttributedString *newAttString = [[NSAttributedString alloc] initWithString:plainString attributes:attributes];
    
    [mutableAttString appendAttributedString:newAttString];
    

    However, just for the sake of getting all the options out there, you could also create a single mutable attributed string, made from a formatted NSString containing the input strings already put together. You could then use addAttributes: range: to add the attributes after the fact to the ranges containing the input strings. I recommend the former way though.