Wrapping a UITextView with a RectWithSize constraint:

I am trying to dynamically update the height of a UITextView using the following code, but the result is sequentially disabled by a few pixels, which causes the text view to wrap, but should not be appropriate. After entering another character (or two), the display is updated accordingly.

I looked at various posts (many are outdated because they refer to outdated sizeThatFits) and I don't see anything else. Those using boundingRectWithSize: (either NSString or NSAttributedString, of which I tried both), look like this:

CGRect boundingRect = [string boundingRectWithSize: CGSizeMake(CGRectGetWidth(textView.frame), CGFLOAT_MAX) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes: @{ NSFontAttributeName : textView.font } context: NULL]; float h = ceil(CGRectGetHeight(boundingRect)); textViewHeightLayoutConstraint.constant = h; 

I know the first thing you're going to say is: inserts. Here is my installation code:

 textView.textContainerInset = UIEdgeInsetsZero; textView.contentInset = UIEdgeInsetsZero; textView.layoutMargins = UIEdgeInsetsZero; 

Are there any other insertion settings?

Side note: I use MuseoSans as a font.

Hacking solution

I β€œfixed” the problem by checking if the width is within the threshold (currently 9px from testing), and if so, pretending to add an extra line:

 float fontHeight = ceil([@"lp" sizeWithAttributes: @{ NSFontAttributeName : textView.font }].height); if ((CGRectGetWidth(textView.frame) - ceil(CGRectGetWidth(boundingRect))) <= 9.f) h += fontHeight; 

The above allows me to capture the maximum possible height and then force its height on my text view. The text view is wrapped accordingly and displays the text on the next line.

Ideas?

Small update

Added this without effect:

 NSMutableParagraphStyle *paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; CGRect boundingRect = [string boundingRectWithSize: CGSizeMake(CGRectGetWidth(textView.frame), CGFLOAT_MAX) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes: @{ NSFontAttributeName : textView.font, NSParagraphStyleAttributeName : paragraphStyle } context: NULL]; 
+5
source share
1 answer

I have found the answer. This is in:

 textView.textContainer.lineFragmentPadding 

I needed to subtract this from my width of the textView. I think there is another source of additions in addition to 3 sets of inserts and fields.

+7
source

Source: https://habr.com/ru/post/1235663/


All Articles