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];