我有一个类似“的Hello Hello ”的文本,它将是一个带有红色的属性字符串。然后在该属性字符串的末尾添加一个nsstring'你是谁?'但是,每当我附加一个nsstring时,整个字符串就会变成普通的nsstring,并且属性字符串的属性将被删除。到目前为止,我的尝试:
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;
我做错了什么?请帮我。
最佳答案
替换底线
NSString *messageWithContact = [NSString stringWithFormat: @"%@ %@", messageTextView.text, @"Who are you?"];
messageTextView.text=messageWithContact;
与
NSMutableAttributedString *newString = messageTextView.attibutedText;
[newString appendAttributedString: [[NSAttributedString alloc] initWithString: @"Who are you?"];
messageTextView.attibutedText = newString;