sizeWithFont doesn't give correct height for UITextView if there is a long string in the text being wrapped

iphone, nsstring, objective-c, uitextfield

Solution

`UITextView` is not exactly like a `UILabel` wrapped in a `UIScrollView`. It has line spacing different from the font size and margins that `sizeWithFont:constrainedToSize:linkBreakMode:` doesn't account for.

Knowing your font size you might be able to calculate the # of lines and take line spacing into account. You can guess at the margins and try to trick `sizeWithFont:` to give a more useful answer.

The popular solutions seem to be:

just use a `UILabel` if you don't need any `UITextView` functionality

if you need `hyperlinks`, overlay `UIButtons` that look like hyperlinks over a `UILabel`

use an off-screen `UITextView` and its `sizeToFit` method to get a real answer

I had no luck w/ the 3rd option but it sounds like it should work, so perhaps I did something wrong.

I'm going to try using a `UILabel` and overlaying buttons for hyperlinks. We'll see how that turns out.

If that fails, there is always the option taken by Loren Brichter (of Tweetie fame): draw everything into a `UIView` yourself using `CoreGraphics`.

Good luck!

Problem

Is there a way to get the correct size of an NSString using: ``` - (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode ``` that doesnt get thrown off by 2 or 3 hundred character strings. At the moment if I try to use this method on these long strings it incorrectly calculates them and I end up with lots of whitespace at the bottom of the UITextView. I've tried using UILineBreakModeWordWrap and UILineBreakModeCharacterWrap. the resizing is being done in ``` - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGFloat result = 44.0f; NSString* text = nil; CGFloat width = 0; CGFloat tableViewWidth; CGRect bounds = [UIScreen mainScreen].bounds; tableViewWidth = bounds.size.width; width = tableViewWidth - 150; text = stringWithLongWords; if (text) { CGSize textSize = { width, 20000.0f }; CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:10.0f] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap]; size.height += 50.0f; result = MAX(size.height, 44.0f+30.0f); } return result; } ```

Original source

Related problems