Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 8 sizeThatFits for UITextView text not returning correct height (AutoLayout)

I'm trying to vertically center a UITextView using the appropriate height retrieved from sizeThatFits. There are a plethora of other answers that suggest this is the most appropriate way of calculating this.

(Note that I've tried it both with plain and attributed strings, and both exert the same behavior).

No matter what I try (even using attributed strings and setting the font size or line height to something bigger or smaller) it always only shows a certain truncated number of characters of text (in this case, 3 lines, and it's always exactly the same). What am I missing?

_textView.text = [_collectionDescription lowercaseString];
_textView.font = [UIFont fontLight:22];
_textView.textColor = [UIColor whiteColor];
_textView.textAlignment = NSTextAlignmentCenter;
_constraintTextViewHeight.constant = ceilf([_textView sizeThatFits:CGSizeMake(_textView.frame.size.width, FLT_MAX)].height);

[_textView setNeedsDisplay];
[_textView updateConstraints];
like image 708
brandonscript Avatar asked Nov 20 '14 23:11

brandonscript


2 Answers

Instead of using sizeThatFits: method, you may use following method: well you can try this:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
NSString *text = _textView.text;
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:attributes
                                 context:nil];
_constraintTextViewHeight.constant = CGRectGetHeight(rect)

This method also considers line breaks in string text

like image 28
Udit Agarwal Avatar answered Sep 18 '22 10:09

Udit Agarwal


As always with AutoLayout, you have to do:

[_textInfoView layoutIfNeeded];

(don't even need the setNeedsDisplay at all).

So, fully working:

_textView.text = [_collectionDescription lowercaseString];
_textView.font = [UIFont fontLight:22];
_textView.textColor = [UIColor whiteColor];
_textView.textAlignment = NSTextAlignmentCenter;
_constraintTextViewHeight.constant = ceilf([_textView sizeThatFits:CGSizeMake(_textView.frame.size.width, FLT_MAX)].height);

[_textView layoutIfNeeded];
[_textView updateConstraints];
like image 92
brandonscript Avatar answered Sep 21 '22 10:09

brandonscript