I have a UITextView
and want to set its height as per its content changes.
How can I get height of the content.
Please guide me.
Thanks in advance.
I have a UITextView
and want to set its height as per its content changes.
How can I get height of the content.
Please guide me.
Thanks in advance.
If you want to calculate height of your UITextView
for some text then you can use such method:
CGSize textViewSize = [text sizeWithFont:[UIFont fontWithName:@"Marker Felt" size:20]
constrainedToSize:CGSizeMake(WIDHT_OF_VIEW, FLT_MAX)
lineBreakMode:UILineBreakModeTailTruncation];
In fontWithName
define font that you are using in UITextView
, in size parameter - size of your text in UITextView
. Replace WIDHT_OF_VIEW
width width of your UITextView
.
textViewSize.height
will contain height that UITextField
to display text without scrolling
[text sizeWithFont:font]
method. What could be simplier? –
Fifi -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; CGRect frame = _textView.frame; frame.size.height = _textView.contentSize.height; _textView.frame = frame; }
You can calculate the size of the text with the method from UIStringDrawing
category:
CGSize textSize = [textView.text sizeWithFont:font
forWidth:textWidth
lineBreakMode: UILineBreakModeWordWrap];
CGSize countentSize = textView.contentSize;
int numberOfLinesNeeded = countentSize.height / textView.font.lineHeight;
int numberOfLinesInTextView = textView.frame.size.height / textView.font.lineHeight;
CGRect textViewFrame= textView.frame;
textViewFrame.size.height = numberOfLinesNeeded * textView.font.lineHeight;
[textView setFrame:textViewFrame];
sizeWithFont
is deprecated .
CGRect rect = [textView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: textView.font}
context:nil];
rect.size.width = ceil(rect.size.width);
rect.size.height = ceil(rect.size.height);
I hope it will help someone. Happy coding.
© 2022 - 2024 — McMap. All rights reserved.