Search code examples
iosobjective-cnsstringnsattributedstring

Add a nsstring at the end of attributed string in textview iOS


I have a text like "Hello There" which will be a attributed string with red color. Then at the end of that attributed string I want to append a nsstring 'Who are you?' But whenever I append a nsstring, the whole string becomes normal nsstring and the property of the attributed string is being removed. My attempt so far:

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Hello There"];
[attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,[attributeString length])];

NSMutableAttributedString *previousAttrString = [[NSMutableAttributedString alloc] initWithString:messageTextView.text];

[previousAttrString insertAttributedString: attributeString atIndex:location];
messageTextView.attributedText = previousAttrString;
messageTextView.font = [UIFont fontWithName:@"Helvetica" size:15];

NSString *messageWithContact = [NSString stringWithFormat: @"%@ %@", messageTextView.text, @"Who are you?"];
messageTextView.text=messageWithContact;

What I did wrong? Please help me.


Solution

  • Replace the bottom lines

    NSString *messageWithContact = [NSString stringWithFormat: @"%@ %@", messageTextView.text, @"Who are you?"];
    messageTextView.text=messageWithContact;
    

    with

    NSMutableAttributedString *newString = messageTextView.attibutedText;
    [newString appendAttributedString: [[NSAttributedString alloc] initWithString: @"Who are you?"];
    messageTextView.attibutedText = newString;