I am using the code below for calculate the height of text, then set this height for UILabel
and UITextView
CGSize targetSize = CGSizeMake(300, CGFLOAT_MAX);
NSString *message = @"The Internet connection appears to be offline.";
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [message boundingRectWithSize:targetSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:FontOpenSanWithSize(14)}
context:context].size;
CGSize size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
// it will return size:width = 299 and size height 20
// => if I use this height and set for UILabel, it can display full content
// => if I use this height and set for UITextView, it can not display full content
It's work perfect for UILabel
but for UITextView
sometime it calculate wrong.
I think the problem happened because the padding (left, right) of UITextView
is bigger than UILabel
.
So how can I calculate the correct size of text for display in UITextView
. Any help or suggestion would be great appreciated.
Like the description image below
With the same size (300), same font, same text but the UITextView
display in 2 lines, but UILabel
in 1 lines.
And my code for calculate height return 20, it not enough for display in 2 lines, so the UITextView
can not display full content
The reason why I need to calculate the height of UITextView
base on text because my UITextView
is in a popup.
And the popup height will depend on the TextView
height