1

I have a UISlider that changes the font size of a UITextView. Before changing the font size, I would like to check if the height of my UITextView will be inferior to the height of its view container. The problem is that sizeToFit and sizeWithAttribute are returning different heights for the same font size.

To do that i'm trying to get the height of my UITextView with a custom fontSize, but i cannot figure out a way to do so, and don't understand why I don't get the same height when I do:

self.photoDescription.text = @"Test"
self.photoDescription.font = [self.photoDescription.font fontWithSize:18];
[self.photoDescription sizeToFit];
NSLog(@"real height %f", self.photoDescription.frame.size.height); 
//getting : 37.5

and:

NSLog(@"calculated height %f", [self.photoDescription.text sizeWithAttributes:@{NSFontAttributeName:[self.photoDescription.font fontWithSize:18]}].height);
//getting: 20.97

same thing for:

CGRect textRect = [self.photoDescription.text boundingRectWithSize:CGSizeMake(320, 300)
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName:[self.photoDescription.font fontWithSize:18]}
                                             context:nil];

CGSize size = textRect.size;
NSLog(@"height %f", size.height);
// getting : 20.97

Any thoughts on this?

aksh1t
  • 5,410
  • 1
  • 37
  • 55
Sancho Sanchez
  • 590
  • 1
  • 6
  • 19
  • 1
    It looks like `self.photoDescription` is including the margins around the text, whereas the other options are just giving you the text exclusive of the text view. (18-point font shouldn't be 37.5 points high). – Aaron Brager May 26 '14 at 20:35
  • How can I calculate the height including the margins? – Sancho Sanchez May 27 '14 at 09:28

1 Answers1

1

I finally found an answer to my question with Jordan Montel Solution: iOS7 UITextView contentsize.height alternative

I used his function to get the width :

- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
    UITextView *textView = [[UITextView alloc] init];
    [textView setAttributedText:text];
    CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}
Community
  • 1
  • 1
Sancho Sanchez
  • 590
  • 1
  • 6
  • 19