Search code examples
objective-cnsmutableattributedstring

NSMutableAttributedString Append in UITextView


I need to append 2 NSMutableAttributedString for my UITextview when user selection different words like the example.

string = @"blabla1 blabla2 blabla3"

in first time the user select @"blabla1"

and the text looks like that @"blabla1 blabla2 blabla3"

and after I select @"blabla3" the result I want to get in My UITextview is @"blabla1 blabla2 blabla3"

now the result I get is @"blabla1 blabla2 blabla3 blabla1 blabla2 blabla3"

that my code :

-(NSMutableAttributedString*)getNSMutableAttributedString:(NSString*)string withRange:(NSRange)range withTextView:(UITextView*)textView
{
if (!str)
{
    str = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont *font = [UIFont boldSystemFontOfSize:16];
    [str addAttribute:NSFontAttributeName value:font range:NSMakeRange(range.location, range.length)];

}
else
{
    NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] initWithString:string];

    UIFont *font = [UIFont boldSystemFontOfSize:16];
    [mutableAttString addAttribute:NSFontAttributeName value:font range:NSMakeRange(range.location, range.length)];

    NSMutableAttributedString *first = str;
    NSMutableAttributedString *second = mutableAttString;

    NSMutableAttributedString* result = [first mutableCopy];
    [result appendAttributedString:second];

    str = result;

}

return str;
}

Solution

  • Attributes can be added multiply times to one string.And you create a new attributedString from string, which don't have attributes. In result you receive @"blabla1 blabla2 blabla3 blabla1 blabla2 blabla3"

    -(NSMutableAttributedString*)getNSMutableAttributedString:(NSMutableAttributedString*)string withRange:(NSRange)range withTextView:(UITextView*)textView
    {
    if (!str)
     {
        str = [[NSMutableAttributedString alloc] initWithAttributedString:string];
        UIFont *font = [UIFont boldSystemFontOfSize:16];
        [str addAttribute:NSFontAttributeName value:font range:NSMakeRange(range.location, range.length)];
     }
    else
      {
        UIFont *font = [UIFont boldSystemFontOfSize:16];
        [str addAttribute:NSFontAttributeName value:font range:NSMakeRange(range.location, range.length)];
      }
    return str;
    }