Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get StringSize to return a useful height?

MonoTouch makes the sizeWithFont methods available through UIView, but it seems to return the font's LineHeight no matter how long the string I pass to it.

string someString = "test string";
UIFont someFont = UIFont.SystemFontOfSize(13f);
SizeF sizeToDisplay = someUIView.StringSize(someString, someFont, Bounds.Width, UILineBreakMode.WordWrap);
// sizeToDisplay = { Width: 58, Height = 16 }
someString = string.Join(" ", Enumerable.Repeat(someString, 500));
sizeToDisplay = someUIView.StringSize(someString, someFont, Bounds.Width, UILineBreakMode.WordWrap);
// sizeToDisplay = { Width: 304, Height = 16 }

Is there some other method I should be using to find the height needed to display an arbitrary block of text in a UITextView?

like image 753
patridge Avatar asked Jan 14 '13 19:01

patridge


1 Answers

This isn't specific to MonoTouch, but you'd have to search for the native NSString.sizeWithFont method to find that answer, so this should help other MonoTouch devs in the future.

For some reason, you will need to hit a different overload for StringSize, one that takes a full SizeF argument instead of a width value. In this case, you just "hack" in a very large height to get the wrapped-text size.

SizeF sizeToDisplay = someUIView.StringSize(someString, someFont, new SizeF(Bounds.Width, float.MaxValue), UILineBreakMode.WordWrap);
// For the larger string: sizeToDisplay = { Width: 307, Height = 1600 }

That forWidth overload of StringSize calls over to the native sizeWithFont:forWidth:lineBreakMode: NSString method. For some reason, when you use this overload, it will truncate your string for measurement purposes.

This method returns the width and height of the string constrained to the specified width. Although it computes where line breaks would occur, this method does not actually wrap the text to additional lines. If the size of the string exceeds the given width, this method truncates the text (for layout purposes only) using the specified line break mode until it does conform to the maximum width; it then returns the size of the resulting truncated string.

Note about UITextView padding

As a side note, using a UITextView with the returned StringSize will result in text that requires scrolling to see (UITextView inherits from UIScrollView) because it includes some forced content padding. You will need to also tweak the content offsets to get what you expect.

someUITextView.ContentInset = new UIEdgeInsets(-8, -8, -8, -8);
like image 199
patridge Avatar answered Nov 01 '22 09:11

patridge