Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust UITextView's width to fit its content without wrapping?

Resizing UITextView to fit height of its content can be achieved like this:

CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

Is there something similar to fit width, without wrapping the content text?

like image 851
S B Avatar asked Sep 21 '11 13:09

S B


1 Answers

1) You can use the NSString UIKit Additions to compute the size taken by the text (and adjust the size of your UITextView accordingly). You may seen an example here.

For example, if you need to know the CGSize that is taken by your NSString if rendered on a single line, use CGSize sz = [_textView.text sizeWithFont:_textView.font] then adjust your frame given this size value.

If you need to know the size taken by your text if rendered on multiple lines, wrapping it if the text reaches a given width, use sizeWithFont:constrainedToSize:lineBreakMode: instead, etc.


2) You may also be interested in the sizeThatFits: and sizeToFit methods of UIView. The first one returns the CGSize (that fits in the given CGSize passed in parameter) so that your UITextView can display all your text. The second actually do the resizing, adjusting the frame for you.

like image 95
AliSoftware Avatar answered Oct 24 '22 13:10

AliSoftware