简体   繁体   中英

NSLineBreakByTruncatingTail on UITextView removing new line breaks

I have a UITextView with attributedText that has multiple new line breaks included in its attributed string.

NSMutableAttributedString *info = [[NSMutableAttributedString alloc] initWithString:@""];

NSAttributedString *title = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat:@"%@\n", item.title] attributes:titleAttributes];

NSAttributedString *description = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n\n", description] attributes:descriptionAttributes]

[info appendAttributedString:bioItemTitle];
[info appendAttributedString:bioItemDescription];

textView.attributedText = info;

I've set the lineBreakMode of the textView's textContainer to NSLineBreakByTruncatingTail.

textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;

The textView's textContainer also has a maximum number of lines.

textView.textContainer.maximumNumberOfLines = 8;

The problem arises when the 8th line of the textView is a new line, and not a line of characters. The textContainer truncates by removing the new line and replacing it with the next line of written characters.

How do I preserve the new line while still setting a lineBreakMode?

See screenshots

Try using UILabel instead of UITextView . It seems to play nicer in regard to truncating a new line.

Random things to try on the off chance you haven't already that aren't even solutions but maybe workarounds, and may not work anyway, but whatever:

  • Change the maximumNumberOfLines to 0 and rely on frames/autolayout to size the text view and its container, perhaps in combination with setting the text container's heightTracksTextView property to true

  • Insert horizontal whitespace or invisibles at the beginning of lines that otherwise only contain a newline #hacky

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