How can I concatenate NSAttributedStrings?

前端 未结 8 1358
野性不改
野性不改 2020-12-04 08:58

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 t

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 09:47

    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.

提交回复
热议问题