Reputation: 1780
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;
}
Upvotes: 1
Views: 866
Reputation: 1144
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;
}
Upvotes: 1
Reputation: 70997
What you should be doing is get str
(the existing attributedText
from the UITextView
) and then add an attribute to the specific range
str = [textView attributedText];
UIFont *font = [UIFont boldSystemFontOfSize:16];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange(range.location, range.length)];
return str;
What you are doing is creating a new attributed string with the same content but different attributes and then appending to the existing attributedText. That is why you see the text repeated twice.
Upvotes: 1