Is there an equivalent to NSString's sizeWithFont:
method that can be开发者_JS百科 used for calculating the height of text in a UITectView for a given width? All of the methods from NSString only operate on a single line from what I can tell.
From Apple's reference for these NSString methods, you could use -sizeWithFont:constrainedToSize:
or -sizeWithFont:constrainedToSize:lineBreakMode:
for "Computing Metrics for Multiple Lines of Text".
CGSize size = [theString sizeWithFont:font
constrainedToSize:CGSizeMake(width, 100000)];
return size.height;
For UITextView
, all you have to do is call -sizeToFit
on the view, and it will automatically resize its height until it can fit all the text available. All you need to do is set the width of the text view, set the text, then call -sizeToFit
. The text view will resize its height just enough to fit all the text.
UPDATE:
Apparently text views only shrink when there's excess height, but they don't grow if there's insufficient height to display all the text. In addition, once you call -sizeToFit
, the text view's y
coordinate is reset back to 0.0f
. So here's what you do:
CGFloat textViewWidth = 300.0f;
CGFloat textViewPadding = 10.0f;
UITextView * textView = [[[UITextView alloc] init] autorelease];
textView.text = ...; // Really long string
textView.frame = CGRectMake(0.0f, 0.0f, textViewWidth, CGFLOAT_MAX);
[textView sizeToFit]; // Shrinks the height to fit all the text
textView.frame = CGRectMake(textViewPadding, textViewPadding,
textViewWidth, textView.frame.size.height);
[self.view addSubview:textView];
First, you set the frame just so you can set the width like you want it. You use CGFLOAT_MAX
to pretty much indicate infinite height. Next, calling -sizeToFit
shrinks the height until it just fits all the text. However, it also resets the y
coordinate, so we go ahead and set the frame again to configure the x
and y
coordinates—in this example, 10.0f
for both x
and y
—, leaving the width alone and keeping the height set to whatever -sizeToFit
calculated.
actually, you could use the property contentSize.
精彩评论