简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM