Resizing UITextView to fit height of its content can be achieved like this:
调整UITextView的大小以适应其内容的高度可以像这样实现:
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?
有没有类似于适合宽度的东西,没有包装内容文本?
1 个解决方案
#1
17
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.
1)您可以使用NSString UIKit Additions来计算文本所采用的大小(并相应地调整UITextView的大小)。你可能在这里看到一个例子。
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.
例如,如果您需要知道NSString在单行上渲染时所采用的CGSize,请使用CGSize sz = [_ textView.text sizeWithFont:_textView.font],然后根据此大小值调整帧。
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.
如果你需要知道文本在多行上渲染时所采用的大小,如果文本达到给定的宽度就包装它,请使用sizeWithFont:constrainedToSize:lineBreakMode:代替等等。
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.
2)您可能也对UIView的sizeThatFits:和sizeToFit方法感兴趣。第一个返回CGSize(适合传入参数的给定CGSize),以便您的UITextView可以显示所有文本。第二个实际上是调整大小,为你调整框架。
#1
17
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.
1)您可以使用NSString UIKit Additions来计算文本所采用的大小(并相应地调整UITextView的大小)。你可能在这里看到一个例子。
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.
例如,如果您需要知道NSString在单行上渲染时所采用的CGSize,请使用CGSize sz = [_ textView.text sizeWithFont:_textView.font],然后根据此大小值调整帧。
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.
如果你需要知道文本在多行上渲染时所采用的大小,如果文本达到给定的宽度就包装它,请使用sizeWithFont:constrainedToSize:lineBreakMode:代替等等。
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.
2)您可能也对UIView的sizeThatFits:和sizeToFit方法感兴趣。第一个返回CGSize(适合传入参数的给定CGSize),以便您的UITextView可以显示所有文本。第二个实际上是调整大小,为你调整框架。