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?
This isn’t specific to MonoTouch, but you’d have to search for the native
NSString.sizeWithFontmethod 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 fullSizeFargument instead of a width value. In this case, you just "hack" in a very large height to get the wrapped-text size.That
forWidthoverload ofStringSizecalls over to the nativesizeWithFont:forWidth:lineBreakMode:NSStringmethod. For some reason, when you use this overload, it will truncate your string for measurement purposes.Note about UITextView padding
As a side note, using a
UITextViewwith the returnedStringSizewill result in text that requires scrolling to see (UITextViewinherits fromUIScrollView) because it includes some forced content padding. You will need to also tweak the content offsets to get what you expect.