在textview iOS中的属性字符串末尾添加一个nsstring

时间:2015-03-04 11:35:33

标签: ios objective-c nsstring nsattributedstring

我的文字类似于" Hello There "这将是一个红色的属性字符串。然后在该属性字符串的末尾,我想添加一个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;

我做错了什么?请帮帮我。

1 个答案:

答案 0 :(得分:9)

替换底线

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;