For example, I have 3 sentences such as @"Long long ago.",@"There is a child.",@"bla bla bla" And I made a method below
- (void)appendText:(NSString*)text
{
NSMutableAttributedString *originalText = [[NSMutableAttributedString alloc] initWithAttributedString:_textView.attributedText];
NSAttributedString *appendText = [[NSAttributedString alloc] initWithString:text
attributes:@{NSForegroundColorAttributeName:DefaultTextColor}];
[originalText appendAttributedString:appendText];
_textView.attributedText = originalText;
}
So I invoked appendText 3 times
[self appendText:@"Long long ago."];
[self appendText:@"There is a child."];
[self appendText:@"bla bla bla."];
The result I expected is
Long long ago.There is a child.bla bla bla.
But the output is
Long long ago.
There is a child.
bla bla bla
Why appendAttributedString show appended string in a new line? How can I put the appended text in one paragraph?
Thanks for any help.
From my own experiences, when you set the attributedText property of UITextView, the text is getting a newline added to it. So when you later retrieve the attributedText from the UITextView, this newline is at the end of the text. So when you append more text, the newline is in the middle (and another one is added to the end).
I don't know if this is a bug in UITextView or possibly NSAttributedString.
One workaround would be to update your code as follows:
- (void)appendText:(NSString*)text {
NSMutableAttributedString *originalText = [[NSMutableAttributedString alloc] initWithAttributedString:_textView.attributedText];
// Remove any trailing newline
if (originalText.length) {
NSAttributedString *last = [originalText attributedSubstringFromRange:NSMakeRange(originalText.length - 1, 1)];
if ([[last string] isEqualToString:@"\n"]) {
originalText = [originalText attributedSubstringFromRange:NSMakeRange(0, originalText.length - 1)];
}
}
NSAttributedString *appendText = [[NSAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:DefaultTextColor}];
[originalText appendAttributedString:appendText];
_textView.attributedText = originalText;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With